Before starting, ensure the following are installed on your machine:
Create a file named HelloWorld.java
with the following content:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, Docker and Java!"); } }
Click on Build => Build Project. It will create a out folder on your project directory
This will generate a Main.class
file.
A Dockerfile is a script that contains instructions for building a Docker image. Create a file named Dockerfile
in the same directory as your Java program with the following content:
# Use the OpenJDK 23 image as the base image FROM openjdk:23 # Create a new app directory for my application files RUN mkdir /app # Copy the app files from host machine to image filesystem COPY out/production/HelloWorldDocker/ /app # Set the directory for executing future commands WORKDIR /app # Run the Main class CMD java Main
Open a terminal or command prompt and navigate to the directory containing the Dockerfile
and HelloWorld.class
. Then, build the Docker image:
docker build -t hello-java .
-t hello-java
: Tags the image with the name hello-java
..
: Specifies the current directory as the build context.Once the image is built, you can run it as a container:
docker run hello-java
You should see the output:
Hello, Docker and Java!
While working through this guide, keep the following key concepts in mind:
openjdk:11-jre-slim
).docker build
: Builds an image from a Dockerfile.docker run
: Runs a container from an image.docker images
: Lists all images on the system.docker ps
: Lists running containers.Try the following tasks to practice what you've learned:
HelloWorld.java
program to print your name.openjdk:17-jre-slim
).Explore these resources to learn more about Docker and Java:
Error: LinkageError occurred while loading main class Main
java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 67.0); this version of the Java Runtime only recognizes class file versions up to 65.0.