0
0
DockerHow-ToBeginner · 3 min read

How to Create a Dockerfile for Java Applications

To create a Dockerfile for a Java application, start with a base image like openjdk, copy your compiled .jar file into the container, and define the command to run it using java -jar. This setup packages your Java app in a container for easy deployment.
📐

Syntax

A basic Java Dockerfile uses these parts:

  • FROM: sets the base image with Java installed.
  • COPY: moves your Java application file into the container.
  • CMD: runs the Java app when the container starts.
dockerfile
FROM openjdk:17-jdk-slim
COPY app.jar /app.jar
CMD ["java", "-jar", "/app.jar"]
💻

Example

This example Dockerfile packages a Java app named app.jar. It uses OpenJDK 17 slim image, copies the jar, and runs it.

dockerfile
FROM openjdk:17-jdk-slim
COPY app.jar /app.jar
CMD ["java", "-jar", "/app.jar"]
Output
When you build and run this Dockerfile, your Java app starts inside the container, outputting its normal console logs.
⚠️

Common Pitfalls

Common mistakes include:

  • Using a base image without Java installed.
  • Forgetting to copy the compiled .jar file into the container.
  • Using CMD with shell form instead of exec form, which can cause signal handling issues.

Always use the exec form of CMD with square brackets.

dockerfile
FROM openjdk:17-jdk-slim
# Wrong: shell form, avoid this
CMD java -jar /app.jar

# Correct: exec form
CMD ["java", "-jar", "/app.jar"]
📊

Quick Reference

InstructionPurpose
FROM openjdk:17-jdk-slimUse Java 17 base image with minimal size
COPY app.jar /app.jarCopy your Java application jar into container
CMD ["java", "-jar", "/app.jar"]Run the Java application on container start

Key Takeaways

Start your Dockerfile with a Java base image like openjdk:17-jdk-slim.
Copy your compiled .jar file into the container using COPY.
Use the exec form of CMD to run your Java app: CMD ["java", "-jar", "/app.jar"].
Avoid base images without Java or missing your app file inside the container.
Test your Docker image by building and running it to confirm your Java app starts correctly.