Running Spring Boot Application on Docker

In this blog, I’m showing how to run a spring boot application on a remote docker server. If you don’t have a docker server yet, see my previous blog about Setting up Docker on Azure with Ubuntu server.

If you don’t have a Spring Boot application to test, you can use my simple HelloWorld (Use command mvn clean package to generate JAR file in target directory).

Transfer JAR file to Remote Server

Use command scp -i privatekey localfile username@remotehost:remotedir.
-i privatekey is required only if you use SSH PKI authentication.

scp -i ~/.ssh/dockerdemo target/hello_world.jar demo@52.187.181.112:~

Connect to remote host and you will see the file there.

ssh demo@52.187.181.112 -i ~/.ssh/dockerdemo
ls -al *.jar

Build Docker Image and Start a Container

Create Dockerfile with the following content:

FROM frolvlad/alpine-oraclejdk8:slim
ADD hello_world.jar app.jar
ENTRYPOINT [ "sh", "-c", "java -jar app.jar" ]

Build the image with command sudo docker build -t imagename directory. Once done, use command sudo docker images to display all images.

sudo docker build -t spring-boot-helloworld .

Use command sudo docker run -d — name containername -p hostport:containerport imagename to start a container and use command sudo docker ps to see active containers.

sudo docker run -d --name helloworld -p 80:8080 spring-boot-helloworld

Use command sudo docker logs containername to see the console log of the container.

sudo docker logs helloworld

Try to send a request to your app using command curl http://localhost. You should get the response back.

demo@dockerdemo:~$ curl http://localhost
Hello world from Spring Boot

Configure Firewall for Public Access

Use command sudo ufw status to display firewall status on Ubuntu server.

demo@dockerdemo:~$ sudo ufw status
Status: inactive

Add port 22 and 80 to allowed ports and enable firewall.

demo@dockerdemo:~$ sudo ufw allow 22
Rules updated
Rules updated (v6)
demo@dockerdemo:~$ sudo ufw allow 80
Rules updated
Rules updated (v6)
demo@dockerdemo:~$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
demo@dockerdemo:~$ sudo ufw status
Status: active
To                         Action      From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)

Go to Azure portal and open resource group of your VM.

Open the item of Network security group.

Go to Inbound security rules and click + Add.

Input your rule name and select a service or port to allow.

Your new rule should appear momentarily.

Show your support

Clapping shows how much you appreciated Chairat Onyaem’s story.