0

Java – Deploy Java CLI Application to Docker Image

With Docker, we can create portable Java CLI applications for various environments by pre-building container images. This 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

The 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 these information:

DockerFile

We need a DockerFile file. Create it in the same project directory. It is used 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 command-prompt in the same directory where the DockerFile is. Note that we specified the artifactId  and version. The file name of the generated jar file is also used here.

We will then get the following console output:

Run the Application

Now we can ran 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/.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert