Docker, Java, Software Development

Java – Deploy Java CLI Application to Docker Image

Docker For Developers

With Docker, we can create portable Java CLI applications for various environments by pre-building container images. These images could make deployment a lot easier and less messy in particularly in Production environments. This post briefly demonstrates how to create a Docker image with a Java CLI application.

Requirements

We used the following for this post.

  • Docker for Windows (Docker Desktop Community)
  • OpenJDK 8
  • SpringBoot
  • Maven

A Java CLI Application

The application is a Spring Boot application generated via Spring Initializr in IntelliJ IDEA. It has this simple main class:

Nothing fancy.

pom.xml

The pom.xml file has this information:

Docker File

First, we need a DockerFile file. Create it in the same project directory. Then, we will use it to build our desired Docker image locally.

Build, Run to Test

Build Project

First, we need to build our Maven project using the following command to create the jar file in the target directory.

Build Docker Image

Next, we invoke the following command in the command prompt in the same directory where the DockerFile is. Note that we specified the artifactId and version. We also used the filename of the jar file here.

We will then get the following console output:

Run the Application

Now we can run our application using the following command.

Running Java CLI app that resides in a Docker image

The --rm  option is to automatically clean up the container and remove the file system when the container exits. Please see https://docs.docker.com/engine/reference/run/. And that’s how we create portable Java CLI applications for various environments by pre-building container images.

This post is part of the Docker For Developers tutorial.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like