How do you dockerize a maven project?

Maven is a build automation tool built based on Project Object ModelPOM for short. Maven is used for project build, dependency management, and documentation. The pom.xml file of a maven-based project holds all the dependencies, repositories, etc., needed to build and run that project.

Dockerizing is the process of packing, deploying, and running applications using Docker containers.

This shot walks you through the process of Dockerizingpacking, deploying & running a maven-based project. At the end of this shot, you will have created a maven project, built a deployable project Docker image, and ran it as a container using Docker CLI.

Prerequisites

In this shot, we will make use of the terminal/command line.

  • Basic knowledge of the terminal is needed

  • Basic knowledge of Docker & Maven is needed

Demo application

Although Maven can be used in the build automation of several programming language projects, Maven is primarily used for Java projects.

To start, open up your terminal. To create a Maven project run:

$ mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-maven-docker-project -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

This creates a maven project my-maven-docker-project.

Change into that directory:

$ cd my-maven-docker-project

Below is a maven project standard structure:

my-maven-docker-project
|-- pom.xml
 -- src
    |-- main
    |    -- java
    |        -- com
    |            -- mycompany
    |                -- app
    |                    -- App.java
     -- test
         -- java
             -- com
                 -- mycompany
                     -- app
                         -- AppTest.java

For demo purposes, open your pom.xml file using an editor of your choice.

In the build section of your pom.xml file remove:

<plugin>
    <artifactId>maven-jar-plugin</artifactId>     
    <version>3.0.2</version>
</plugin>

And replace it with:

<plugin>
    <!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.0</version>
      <configuration>
        <archive>
          <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>com.mycompany.app.App</mainClass>
          </manifest>
        </archive>
      </configuration>
</plugin>

Why this? because we created our Maven project via the terminal, as a MANIFEST.MF file wouldn’t be added when we create a jar file. The updated version of the maven-jar-plugin adds a MANIFEST.MF file when jar is created.

For demo purposes, we are going to create a simple web server. Our web server prints out “Hello, World!!! I just Dockerized a Maven Project” when a client (browser) accesses the project over port 8080.

We can add a web server in App.java:

package com.mycompany.app;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class App
{
public static void main( String[] args ) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "<h1> Hello World!!!! I just Dockerized a Maven Project </h1>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}

Dockerizing a Maven project

Docker is used to develop, ship, and run applications. Docker enables you to separate your applications from your infrastructure so that you can deliver software quickly.

Why Dockerize a project?

Docker provides a way out of the mess of version clashes, esoteric build failure messages, and missing dependency errors by reducing the task of installing and running software to as little as two commands (docker run and docker pull). Source

Creating a Dockerfile

For you to Dockerize a Maven project or any project at all, you need a Dockerfile.

A *Dockerfile is a text/script configuration file that contains collections of commands that will be automatically executed, in sequence, in the Docker environment to build a new Docker image.

Let’s Dockerize the maven project we’ve created:

$ touch Dockerfile

Adding a Dockerfile our project directory will look like this:

my-maven-docker-project
|-- pom.xml
 -- Dockerfile
 -- src

In order to use our Dockerfile in Dockerizing our project, we first need to create a Java ARchive jar file for the project.

Open the pom.xml in the build profile and add a finalname. This finalname will be our jar name.

<build>
  <finalName>my-maven-docker-project</finalName>
</build>

Then to generate our jar run:

$ mvn install

The jar file can be located in target/ directory.

In our Dockerfile we will write the following commands:

FROM openjdk:8
ADD target/my-maven-docker-project.jar my-maven-docker-project.jar
ENTRYPOINT ["java", "-jar","my-maven-docker-project.jar"]
EXPOSE 8080

In the above Dockerfile, the:

  • FROM keyword tells Docker the base image on which we want our image built. In our case, OpenJDK 8 official docker image.

  • ADD keyword adds the jar we’ve created getting it from the new /target directory.

  • ENTRYPOINT keyword specifies commands to run the jar file.

  • EXPOSE keyword makes port 8080 available outside the Docker container.

Docker container is a running instance of a Docker image. A Docker image is a read-only template with instructions for how to create a Docker container.

Building a Docker image

To build our Docker image using the Dockerfile, run:

$ docker build -t my-maven-docker-project.jar .

The above command:

  • Builds our project, naming it my-maven-docker-project.jar

  • Tags the image via the -t flag

  • Tells Docker to look for the docker file in the same directory via the .

Running a Docker image

Finally, we can run our project by starting a Docker container with the previously built image and binding port 8080 on our local machine.

$ docker run -p 8080:8080 my-maven-docker-project.jar

The command above:

Runs the Docker image and -p publishes the container’s port 8080 to the host (your machine) port 8080.

We can now access localhost:8080 with a browser and see the “Hello, World!!! I just Dockerized a Maven Project” message from the webserver.

localhost:8080
localhost:8080

Conclusion

In this shot, we learned how to Dockerize a Maven project by primarily using the terminal. We also saw why and how we could use Docker to build scalable software quicker.

Thank you for reading! If you found this article helpful, react and share. Cheers! You can follow me on Twitter.

Free Resources