How to connect and deploy application from docker container to EC2 instance

In this article, I will be showing how to run and deploy the angular project from Docker Container(Localhost) to the Amazon EC2 instance.

I have made a video and uploaded it on Youtube. This is the theoretical article.

First, I have taken a base Ubuntu OS in docker and installed Angular, Nodejs, JDK, Jenkins and created a new image, which I pushed to my repository. After doing that I ran my docker container by this cmd

docker run -it -d -p 8095:8080 -p 81:80 -p 50000:50000 image_id. For entering into container type this cmd

docker exec -it container_id bin/bash.

After entering into the container you will be logged in root user. Run this command “service Jenkins start”.You will get a message as Jenkins started on some pid number. If you are using a MAC OS the jenkins URL will be localhost and the port number which you entered when you started the container. I am running it on port 8095 so my URL will be “localhost:8095”. If you are using windows then your jenkins url will be 192.168.99.100: port number. it’s because of the NAT setting in the network.

Now create an EC2 instance using Ubuntu any version. I am using 18.04. log into instance. By default you will ubuntu user. Now run “sudo apt-get update” this cmd will update packages. And install apache2 in an instance.

“sudo apt-get install apache2 -y” by running this cmd apache will be installed. Now run “sudo service apache2 start” to start Apache service in an instance.

Now go to your docker container and switch to jenkins user. I have created a user called jenkins by using “useradd jenkins” cmd and set a password for the user by”passwd jenkins” cmd. To switch to jenkins user

“su – jenkins”. Now run “ssh-keygen” hit enter until you get the message that key has been created. Now this key will be under jenkins folder i.e, /usr/lib/jenkins/.ssh/id_rsa.pub. view that key by “cat /.ssh/id_rsa.pub” and copy that key. And go to ec2 instance, here you are logged in as ubuntu user run “ls -la”. You will find .ssh folder in your home directory. In that folder, there will be a file called authorize_keys open it and paste the key that you copied from your docker container by “sudo vi authorize_keys”. Once done go back to your docker container and run “ssh ubuntu@public-ip-address”. If everything is working fine you will be welcomed as ubuntu user inside ec2 instance. run “exit” to exit from ssh connection.

Now go to your jenkins url and create a new job or project. Under source management, select git. And add the git repository and under build section select “execute as shell”. And add these cmds “npm install”, “ng build”, “cd dist”, “tar -czvf new-name.tar.gz *”, “scp new-name.tar.gz instance-2-user@public-ip-address:folder” apply and save it. Now click on Build. The build is successful

.