Dockerizing Spring Boot Application

In my previous post, I mentioned about How to run docker container on your local machine. This post is about the dockerizing backend part of the Nutrition Tracking Application. We will follow these steps:

  1. Building Spring Boot project
  2. Writing a Dockerfile
  3. Building and running docker image

Step 1: Building Spring Boot project

mvn clean packagewill produce a .jar file into build directory, which is targetby default. If build is successfull, you should be able to see target folder in your project root directory. If you define <artifactId> and <version> tags in pom.xml as follows, the result will be target/demo-0.0.1-SNAPSHOT.jar


Step 2: Writing a Dockerfile

FROM java:8
ADD target/demo-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -jar /app.jar" ]

The Dockerfile above enables a Java runtime to run the demo-0.0.1-SNAPSHOT.jar, which we build in Step 1. Let’s explain what we did here in detail:

  • FROM: Initializes a new build stage and sets the base image for subsequent instructions.
  • VOLUME: Creates a new mount point at /tmp. The reason is that a Spring Boot application creates working directories at /tmp for Tomcat by default. According to the guide, this might be needed for Spring Boot applications if they need to actually write in the filesystem.
  • ADD: Copies target/demo-0.0.1-SNAPSHOT.jar and add it to the filesystem of the image at the path app.jar.
  • EXPOSE: Enables container to listen on the 8090 port at runtime.
  • ENV: Sets the environment variables in the container.
  • ENTRYPOINT: Executes app.jar.

Step 3: Building and running docker image

  1. Open Docker Quickstart Terminal
  2. Go to project root directory (e.g.: cd /c/_Continious Development/Personal Projects/NutritionTrackingApp/NutritionTrackingBackend)
  3. Build and run image
$ docker build -t nutrition .

$ docker run -p 8080:8090 -it nutrition

.Step 4: Test

We can test our REST service via postman or curl.

Alternatively, use curl by opening a new terminal.

We need to use the default docker machine IP ( in order to access docker container running in Linux from the host machine running in Windows. You can learn yours when you start the Docker Quickstart Terminal.


Leave a Reply

Your email address will not be published. Required fields are marked *