Master java skills

Docker Java Tutorial

How to Dockerize a java application Example

In this example, we will see how to dockerize a java application. Meaning, how to run a core java application using docker

Step 1. Create a maven application with a main class

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sks</groupId>
	<artifactId>docker-example-app</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	
	<properties>
		<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
	</properties>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>${maven-jar-plugin.version}</version>
				<configuration>
					<archive>
						<manifest>
							<mainClass>com.sks.Hello</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Hello.java

package com.sks;

public class Hello {
	public static void main(String[] args) {
		System.out.println("Welcome to java application");
	}
}

2. Run As Maven install

Step 3. Go to the root of the project and write the Docker file

From openjdk:11
MAINTAINER com.sks
COPY target/docker-example-app-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
  • First line, OpenJDK Java version 11 image is being imported as our base image from java official repository. The next lines will create additional layers on top of this base image.
  • In the second line, the maintainer for our image is specified. It is com.sks in this case. But it doesn’t create any additional layers.
  • In the third line, a new layer is created by copying the generated jar, docker-example-app-0.0.1-SNAPSHOT.jar, from the target folder of the project into the root folder of our container with the name app.jar.
  • And in the last line, the main application with the unified command that is executed for this image is specified. We instruct here the container to run the app.jar using the java -jar command. This line also does not introduce any additional layer.

Step 4. Build and run the docker image

Build the docker image by running the below command on command prompt from the root directory of your project

docker image build -t docker-java-jar:helloImage .

If you go and check DockerDesktop application, you will find a new image by the name helloImage

run the docker image by running the below command

docker run docker-java-jar:helloImage

We are getting the output as – Welcome to java application