In this tutorial, we will learn how to create a simple Java Hello World program and deploy it in Docker container.
Prerequisites
- Java Development Kit (JDK) installed on your local machine.
- Docker installed and running on your local machine.
- Text editor
Step-by-Step Guide
1. Writing the Java Application
Let's start with a basic Java program.
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Docker World!");
}
}
Save the file as HelloWorld.java.
2. Compiling the Java Application
You can check whether your program compiles or not by using the following command:
javac HelloWorld.java
This will produce a bytecode file named HelloWorld.class that can be run on the Java Virtual Machine (JVM).
3. Creating a Dockerfile
The Dockerfile is a script used by Docker to create a Docker image. Here's a basic Dockerfile to run our Java application:
# Use the official openjdk image as the base image
FROM openjdk:11-jdk-slim
# Set the working directory in the Docker container
WORKDIR /app
# Copy the HelloWorld.java file into the Docker container
COPY HelloWorld.java .
# Compile the HelloWorld.java file
RUN javac HelloWorld.java
# Specify the command to run when the Docker container starts
CMD ["java", "HelloWorld"]
Save this file as Dockerfile in the same directory as your Java program.
4. Building the Docker Image
Navigate to the directory containing your Java program and Dockerfile. Then, build the Docker image using the following command:
docker build -t hello-world-java .
This command tells Docker to build an image using the Dockerfile in the current directory (.) and tag it (-t) as hello-world-java.
5. Running the Docker Container
Once the image is built, you can run your Java application inside a Docker container:
docker run hello-world-java
You should see the output:
Hello, Docker World!
Congratulations! You've successfully dockerized your Java application.
Conclusion
Containerizing applications with Docker offers many benefits, including consistent environments, isolation, and portability. With just a few steps, we were able to run our Java "Hello World" application inside a Docker container, making it ready for more complex deployment scenarios. This basic example serves as a foundation for dockerizing more complex Java applications in the future.
Happy Dockerizing!
Comments
Post a Comment
Leave Comment