Dockerizing Your Spring Boot Application

In this post we will be creating a docker container that will run the sample application from the spring boot getting started guide.

Checkout the Sample

We start with downloading the source code from github.

git clone https://github.com/spring-guides/gs-spring-boot.git  

Change into the project directory, and build it.

cd gs-spring-boot/complete/  
mvn package  

Now we will create a dockerfile to describe our container image. You can create this file in the project root for now.

Dockerfile

FROM java:8  
EXPOSE 8080  
CMD java -jar -Djava.security.egd=file:/dev/./urandom gs-spring-boot-0.1.0.jar  
ADD target/gs-spring-boot-0.1.0.  

Let's look at each line

FROM java:8

This tells docker to base this container from the official java container tagged with "8". More specifically OpenJDK 8. You can check out other options from the offical java repository.

EXPOSE 8080

Expose tells docker what network ports the container will be listening at runtime. You can than make this port available to the host or other containers. More common scenario is to use a reverse proxy container, and forward requests coming to a specific domain name to this port. I will cover this in a later post.

CMD java -jar -Djava.security.egd=file:/dev/./urandom gs-spring-boot-0.1.0.jar

CMD specifies the command that will run when the container is initialized. We just run our spring boot application with a security setting that will speed up tomcat startup.

ADD target/gs-spring-boot-0.1.0.jar .

This will just add our application jar file inside the container.

Check out the Dockerfile reference for other options.

The Container

Let's first build the docker container that we just defined.

docker build -t spring-boot-docker .  

spring-boot-docker is the name that we have given our container. We are going to use this name in future docker commands.

Running it All

docker run -p 8080:8080 -t spring-boot-docker  

You can browse to http://localhost:8080 to see it in action.

Note to OSX and Windows users. docker is not native to your operating system. You are most probably using boot2docker. If so, use the ip address of your docker virtual machine instead of localhost