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 | <build> |
Add Dockerfile
1 | FROM adoptopenjdk:11-jre-hotspot |
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 | mvn clean package |
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 | <properties> |
Navigate to project folder and execute commands to package the application. Now docker container will be generated automatically.
1 | mvn clean package |
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 | FROM maven:3.6.3-jdk-11-slim as builder |
Reference
source code - SpringBootExamples - docker