Spring boot containerized deployment in AWS EC2 in 10 steps

Kavindu Gayan
4 min readDec 2, 2020

This tutorial explains about how to deploy spring boot application using docker in AWS EC2 instance.

Introduction

As simply we are going create image locally and push it to docker hub. Then that image pull and deploy on Amazon EC2 instance.

figure 1

Requirements

Docker desktop
Maven installed on local machine
GIT installed on local machine
Docker hub account
AWS account

Step 1

Clone the sample spring boot project from GitHub https://github.com/KavinduGayan/ec2-docker.git or you can create your own spring boot project from spring initializr or any other prefer method.

git clone https://github.com/KavinduGayan/ec2-docker.git

Step 2

Run and verify the project, working or not.

figure 2

Step 3

Build the project using “mvn clean package” command. Which creates the jar file in the target directory. (see figure 3)

mvn clean package

Step 4

Check the docker file. which is inside the ec2-docker directory.

figure 3
#jdk version 8
FROM openjdk:8-jdk-alpine
#get jar file from target directory
ARG JAR_FILE=target/*.jar
#copy it to app.jar
COPY ${JAR_FILE} app.jar
#running commands/instructions
ENTRYPOINT ["java","-jar","/app.jar"]

Step 5

Now you can build the image using docker build command. -t means tag name <your_user_name>/<image_name> and “.” means all.

figure 4

You can check and verify the image.

docker image ls

figure 5

Since image has been created successfully. Now we can run that image for test and verify.

docker run -p 8080:8080 kavdoc93/docker-ec2-example

figure 6

check and verify the http://localhost:8080/test.

Step 6

Now image is ready to push to the docker hub. Before push to the docker hub you have to login to the docker hub.(see figure 7)

docker login — —username=<user_id>

figure 7

docker push kavdoc93/docker-ec2-example

figure 8
figure 9

After successful push any one can see the repository in the docker hub.

figure 10

Next thing is creating a EC2 instance in AWS. I hope you guys are knowing these thing and which are not relevant to topic.

Step 7

I have created Amazon Linux 2 EC2 server and next step is installing the docker.

Amazon Linux 2
sudo amazon-linux-extras install docker

Amazon Linux.
sudo yum install docker

sudo service docker start

sudo usermod -a -G docker ec2-user

verify with new session
docker info

For more details for the docker installing on Amazon Linux. Please refer https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html

Step 8

Now you can pull the image from docker hub. Before that you have to login (see step 6).

docker pull kavdoc93/docker-ec2-example

figure11
figure 12

Step 9

Let’s check and run the image.

figure 13

To run the image see the Step 5.

Step 10

Let’s check the result.

<public_ip_of_ec2>/test

figure 14

Please note that you have add inbound rules to allow 8080 port from EC2 security group.

--

--