Docker and Java: A Step-by-Step Guide

Due date 6/29

Step 1: Prerequisites

Before starting, ensure the following are installed on your machine:

Step 2: Write a Simple Java Program

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!");
    }
}

Step 3: Build Project

Click on Build => Build Project. It will create a out folder on your project directory

This will generate a Main.class file.

Step 4: Create a Dockerfile

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

Step 5: Build the Docker Image

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 .

Step 6: Run the Docker Container

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!

Step 7: Key Concepts

While working through this guide, keep the following key concepts in mind:

Step 8: Practice Exercise

Try the following tasks to practice what you've learned:

  1. Modify the HelloWorld.java program to print your name.
  2. Update the Dockerfile to use a different base image (e.g., openjdk:17-jre-slim).
  3. Build and run the updated Docker image.

Step 9: Additional Resources

Explore these resources to learn more about Docker and Java:

Step 10: If you see the following error

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.

💡 How to Submit on Blackboard?

  1. Break down all the requirements into stories on the GitHub project.
  2. Push the code to GitHub with solutions.
  3. Write about the use of docker in the README.md file.
  4. Submit your GitHub project url , GitHub code url, and output screenshot on Blackboard.