To package our application, we’re going to be using Docker. The natural build language for Docker images are Dockerfile
s, 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.
Dependencies
To build the source, you will need JDK 8+, and a Docker installation.
Dockerfile
First create the Dockerfile to construct our image, as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
You can see that we are basing image on the official openjdk:jre-alpine
image. This will give us the latest Java JRE release based on the Alpine Linux distribution.
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 overridded 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 times.
Maven POM file
Now we need to add a pair of properties to configure the image builder:
1 2 3 4 5 6 |
|
In the plugins
section, we also need to add the actual Dockerfile Maven plugin. There are only two interesting parts to this:
- The
executions
section, to wire up the Dockerfile build bases to the default ones. - The
dependencies
section, which makes this plugin work against later versions of the JDK.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Building
Once this is complete, the Docker image can be built simply by running:
./mvnw package