Spring Boot - Dockerizing Spring Boot App

Let’s learn how to dockerize a Spring Boot Application.

Adding Dockerfile

First set the final jar file name in pom.xml

1
2
3
<build>
<finalName>DemoSpringBootApp</finalName>
</build>

Add Dockerfile

1
2
3
4
FROM adoptopenjdk:11-jre-hotspot
EXPOSE 8080
ADD /target/DemoSpringBootApp.jar /app/
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app/DemoSpringBootApp.jar"]

There is no need to use jdk, jre will be enough to run java applciation.

-Djava.security.egd=file:/dev/./urandom is less secure on Linux but allows faster startup. see Avoiding JVM delays caused by random number generation - by Marko

Dockerize Application Manually

Navigate to project folder and execute commands to build and run application. image name is xinghua24/demospringbootapp.

1
2
3
mvn clean package
docker build -f Dockerfile -t xinghua24/demospringbootapp .
docker run -p 8080:8080 -t xinghua24/demospringbootapp

dockerfile-maven Plugin

Use Maven plugin dockerfile-maven-plugin is more convenient than manually build the container.

dockerfile-maven-plugin has the following goals

  • dockerfile:build - build Docker image from Dockerfile
  • dockerfile:tag - tag a Docker image
  • dockerfile:push - push Docker image to a repository

add the following snippe to pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<properties>
<dockerfile-maven-version>1.4.8</dockerfile-maven-version>
</properties>

<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>${dockerfile-maven-version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>xinghua24/demospringbootapp</repository> <!-- image name -->
</configuration>
</plugin>

Navigate to project folder and execute commands to package the application. Now docker container will be generated automatically.

1
2
3
4
mvn clean package

# to start the application
docker run -p 8080:8080 -t xinghua24/demospringbootapp

Multistage Build

Nowadays it is very common to have two stage build that can build artifact from source and run it. Here is an example Dockerfile that does the two stage build. Problem with this approach is it is very time consuming for maven to download dependencies and build the jar file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FROM maven:3.6.3-jdk-11-slim as builder

# Copy local code to the container image.
WORKDIR /app
COPY pom.xml .
COPY src ./src

# Build a release artifact.
RUN mvn package -DskipTests

FROM adoptopenjdk:11-jre-hotspot

# Copy the jar to the production image from the builder stage.
COPY --from=builder /app/target/app-*.jar /app.jar

ENV PORT 8080

# Run the web service on container startup.
CMD ["java","-Djava.security.egd=file:/dev/./urandom","-Dserver.port=${PORT}","-jar","/app.jar"]

Reference

source code - SpringBootExamples - docker