Building Docker images with Maven
To package our application, we’re going to be using Docker. The natural
build language for Docker images are
Dockerfiles, so we will use
Spotify’s Dockerfile Maven plugin.
This post is part of the “Spring Boot Primer” series.
To make packaging as simple as possible, we will bind the Maven plugin’s
build phases to the default build phases, so that when you type
./mvnw package, your Docker image will be built.
First create the Dockerfile to construct our image, as below:
You can see that we are basing image on the official
This will give us the latest Java JRE release based on the Alpine Linux
We add an argument
ARG JAR_FILE to parameterise the Docker image build. This will
allow Maven to provide us with the name of the JAR file to package.
We create a
/tmp volume to speed up second launch times of the containers, as this
is where the embedded application container stores its exploded contents to.
We set up an environment variable
ENV _JAVA_OPTIONS to configure the JVM to
some sensible values for hosting a web service. The default values here can easily
be overridden when composing this image later.
We add a user and group for the image, so that the application does not run as root.
Lastly we tell Java to use
/dev/urandom for its random number seed to improve boot
Maven POM file
Now we need to add a pair of properties to configure the image builder:
plugins section, we also need to add the actual Dockerfile Maven plugin.
There are only two interesting parts to this:
executionssection, to wire up the Dockerfile build bases to the default ones.
dependenciessection, which makes this plugin work against later versions of the JDK.
Once this is complete, the Docker image can be built simply by running: