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:
- Building Spring Boot project
- Writing a Dockerfile
- 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
<artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version>
Step 2: Writing a Dockerfile
FROM java:8 VOLUME /tmp ADD target/demo-0.0.1-SNAPSHOT.jar app.jar EXPOSE 8090 ENV JAVA_OPTS="" ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -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
- Open Docker Quickstart Terminal
- Go to project root directory (e.g.: cd /c/_Continious Development/Personal Projects/NutritionTrackingApp/NutritionTrackingBackend)
- 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 (192.168.99.100:8080) 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.