Dockerize your Java Application

Garrett Sweeney
Dec 6, 2018 · 6 min read

A quick word on Docker

Why Docker? It solves the problem of “it runs on my machine”. Instead of delivering jars, wars, whatever — you deliver “images”.

Get Setup Locally

I’m working on a Mac, so I’ll give a short description on how I got set up. If you’re working on something else, this is all pretty google-able.

Look! A whale to the left
$ docker --version
Docker version 18.09.0-ce, build 4d60db4

Clone a sample Java application

As I said in the introduction, I’m going to clone a sample spring.io/guides app. I’ll then build the Dockerfile to dockerize this java app.

git clone https://github.com/spring-guides/gs-serving-web-content.git
cd ./complete
touch Dockerfile

Another word on Docker

Before I start adding commands to the Dockerfile, let me give you the gist of what a Dockerfile does.

Building the Dockerfile

Like I just said, we have to choose an image to start with. I’m going to start with Ubuntu. To make our base image Ubuntu, add this line:

FROM ubuntu:latest
RUN \
# Update
apt-get update -y && \
# Install Java
apt-get install default-jre -y
ADD ./target/gs-serving-web-content-0.1.0.jar spring-mvc-example.jar
EXPOSE 8080
CMD java -jar spring-mvc-example.jar

A third word on Docker

At this point I hope you realize the benefit of docker, as we can control the machine where our application is running.

Let’s Build and Run the Image Locally

I’ll reiterate that we need to have our jar built at this point. If you have not built the java project, do so now:

java -version
mvn --version
mvn clean install
docker build . -t spring-mvc-sample-image
$ docker imagesREPOSITORY                TAG                 IMAGE ID            CREATED             SIZEspring-mvc-sample-image   latest              8fa27ad00edd        34 minutes ago      540MB
docker run -t -p 8080:8080 --name sample-mvc-sample-container spring-mvc-sample-image
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
736f9cdc1499 spring-mvc-sample-image "/bin/sh -c 'java -j…" 2 hours ago Up 2 hours 8080/tcp sample-mvc-sample-container

Finally, tag and push the Image to the public Dockerhub

First, list the image and find the one you built

$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEspring-mvc-sample-image latest 8fa27ad00edd 34 minutes ago 540MB
docker tag 8fa27ad00edd gsweene2/spring-mvc-sample-image:0.1
docker push gsweene2/spring-mvc-sample-image:0.1

Find your image in DockerHub

You should be able to find it at cloud.docker.com after you log in, but the URL pattern appears to be:

Faun

The Must-Read Publication for Aspiring Developers & DevOps Enthusiasts

Garrett Sweeney

Written by

Faun

Faun

The Must-Read Publication for Aspiring Developers & DevOps Enthusiasts