Package a Spring Boot Application with Docker

In this article, I will describe how we can easily package our Spring Boot Java Application into a Docker container using the docker-maven-plugin

The reason why we favor containers in our Continuous Delivery (CD) prototyping is that they offer greater isolation than Virtual Machines (VMs). When the number of applications deployed on a VM grows, the chance of dependency conflicts (e.g. JDK or System Libraries) is very high. Containers are also lightweight, portable and fast to create and destroy. Lastly there are several orchestration technologies out there, like Kubernetes and Mesos, that make working with containers a breeze.

Firstly, you need to define a remote docker host by the setting the DOCKER_HOST environment variable on the machine you are going to execute the build.

Docker by default runs on a non-networked socket and does not connect to unprotected registries. If you want to expose it over the network and have it connect to your private registry over HTTP you need to include the following options in its configuration file /etc/sysconfig/docker

Finally, we restart docker and launch the registry

Make sure to replace the IPs with the correct ones.

Create the Dockerfile

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using the docker build command users can create an automated build that executes several command-line instructions in succession.

Place the following Dockerfile in /src/main/docker

Setup the Docker Maven Plugin

In the pom.xml add this plugin configuration

That’s all! Now you can run your build.

Run you build

Once the build is complete you can go on any docker enabled machine configured to connect to your registry and run your application:

Get the sample from Git

You can get the code for this tutorial on https://github.com/marcolenzo/spring-boot-docker-spotify