Docker Java: Dockerize a Java Application
To dockerize a Java application means packaging the JAR, a Java runtime and the start command into one container image that runs the same way on any machine with Docker. The server no longer needs Java installed, and "it works on my machine" problems disappear because everyone runs the exact same image. Containers are also the standard way to deploy to the cloud and to Kubernetes.
This lesson takes the CourseServer app from Java Deployment, writes a Dockerfile for it, improves it step by step (multi-stage build, non-root user, memory limits, health checks) and finishes with Docker Compose. All examples were run with Docker 28 and JDK 21.
Docker Basics for Java Developers
| Term | Meaning | Java comparison |
|---|---|---|
| Image | A read-only package: OS files + Java + your JAR | Like a JAR, but includes the runtime |
| Container | A running instance of an image | Like a running JVM process |
| Dockerfile | The recipe that builds an image | Like pom.xml for the image |
| Registry | A server that stores images (Docker Hub, GHCR) | Like Maven Central |
| Tag | A version label, e.g. course-server:1.1.0 | Like the project version |
How it works:
- An image is built in layers. Each Dockerfile instruction adds a layer, and unchanged layers are reused from cache on the next build.
- A container is isolated from the host: it has its own file system, network and process list, but shares the host's Linux kernel.
Write Your First Dockerfile for a Java App
Start with the JAR you already built (target/course-server-1.1.0.jar) and the official Eclipse Temurin Java image.
# Dockerfile
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/course-server-1.1.0.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
| Instruction | What it does here |
|---|---|
FROM eclipse-temurin:21-jre | Base image: Ubuntu + Java 21 runtime (no compiler) |
WORKDIR /app | Creates /app and makes it the current folder |
COPY ... app.jar | Copies the JAR from your project into the image |
EXPOSE 8080 | Documents the port the app listens on |
ENTRYPOINT [...] | The command that runs when the container starts |
docker build -t course-server:1.1.0 .
docker image ls course-server --format "{{.Repository}}:{{.Tag}}"
[+] Building 6.4s (8/8) FINISHED
=> [internal] load build definition from Dockerfile
=> [1/3] FROM docker.io/library/eclipse-temurin:21-jre
=> [2/3] WORKDIR /app
=> [3/3] COPY target/course-server-1.1.0.jar app.jar
=> exporting to image
=> => naming to docker.io/library/course-server:1.1.0
course-server:1.1.0
How it works:
-t course-server:1.1.0names and tags the image. Always tag with the real version, not onlylatest, so you know what each server runs.- The final
.is the build context: the folder whose filesCOPYcan see. - Use the
-jreimage to run apps. The-jdkimage includesjavacand other tools a running server does not need, making the image larger.
Run a Java Container
docker run -d --name course -p 8080:8080 -e APP_ENV=prod course-server:1.1.0
docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
docker logs course
curl -s -w "\n" http://localhost:8080/health
NAMES IMAGE STATUS PORTS
course course-server:1.1.0 Up 3 seconds 0.0.0.0:8080->8080/tcp
CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
{"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":3}
Common docker run Options
| Option | Example | Meaning |
|---|---|---|
-d | -d | Run in the background |
--name | --name course | A fixed name instead of a random one |
-p host:container | -p 80:8080 | Publish container port 8080 on host port 80 |
-e KEY=value | -e APP_ENV=prod | Set an environment variable |
--env-file | --env-file app.env | Load many variables from a file |
--memory | --memory 512m | Hard memory limit for the container |
--restart | --restart unless-stopped | Restart after crashes and Docker restarts |
--rm | --rm | Delete the container when it stops |
How it works:
-p 8080:8080maps the host's port to the container's port. Without it, the app runs but nobody outside the container can reach it.- The app reads
APP_ENVwithSystem.getenv, exactly as on a normal server. Environment variables are the main way to configure containers, as covered in Java Environment Variables. docker logsshows everything the JVM printed to stdout and stderr, so Java apps in containers should log to the console, not to files.
Stop a Java Container Gracefully
docker stop sends SIGTERM to the main process, waits 10 seconds, then sends SIGKILL.
docker stop course
docker logs course | tail -n 2
docker inspect course --format "exit code: {{.State.ExitCode}}"
Shutting down...
Stopped.
exit code: 143
How it works:
- The exec form
ENTRYPOINT ["java", ...]makesjavaprocess 1 in the container, so it receives the signal directly and the shutdown hook runs. - The shell form
ENTRYPOINT java -jar app.jarwould start/bin/shas process 1. The shell does not pass SIGTERM on, so Docker kills the JVM after 10 seconds without a clean shutdown. - Exit code 143 (128 + 15) means "stopped by SIGTERM", which is the normal result.
Multi-Stage Builds: Build the JAR Inside Docker
The first Dockerfile needs a JAR built on your machine. A multi-stage build compiles the code inside Docker too, so the build only needs Docker, not Maven or a JDK.
# Dockerfile
# ---------- stage 1: build ----------
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /build
COPY pom.xml .
RUN mvn -q dependency:go-offline # cached until pom.xml changes
COPY src ./src
RUN mvn -q -DskipTests package
# ---------- stage 2: run ----------
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /build/target/course-server-*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t course-server:1.1.0 .
# change one line in a .java file, then build again
docker build -t course-server:1.1.0 . 2>&1 | grep -E "CACHED|RUN mvn"
=> CACHED [build 2/6] WORKDIR /build
=> CACHED [build 3/6] COPY pom.xml .
=> CACHED [build 4/6] RUN mvn -q dependency:go-offline
=> [build 6/6] RUN mvn -q -DskipTests package
How it works:
- Only the last stage becomes the final image. Maven, the JDK and the source code stay in the build stage and are thrown away.
- Copying
pom.xmlbeforesrcis the key trick. Dependencies are downloaded in their own layer, which stays cached while you only change Java code. Rebuilds take seconds instead of minutes. - Add a
.dockerignorefile withtarget/and.git/so those folders are not sent to Docker as part of the build context.
Run the Container as a Non-Root User
By default the process inside a container runs as root. Create a normal user and switch to it.
FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=build --chown=app:app /build/target/course-server-*.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t course-server:1.1.0 .
docker run --rm --entrypoint id course-server:1.1.0
uid=999(app) gid=999(app) groups=999(app)
How it works:
USER appapplies to every later instruction and to the running container. If the app is attacked, the attacker is not root inside the container.--chown=app:appgives the copied JAR to the new user in the same layer.--entrypoint idreplacesjavafor one run, a quick way to see which user the image runs as.
Set Java Memory Correctly in Containers
The JVM is container-aware: it reads the container's memory limit, not the host's total memory. By default it uses only 25% of that limit for the heap, which is low for a container that runs nothing else.
docker run --rm --memory 512m --entrypoint java course-server:1.1.0 \
-XX:+PrintFlagsFinal -version 2>/dev/null | grep -E " MaxHeapSize"
docker run --rm --memory 512m -e JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75" \
--entrypoint java course-server:1.1.0 \
-XX:+PrintFlagsFinal -version 2>/dev/null | grep -E " MaxHeapSize"
size_t MaxHeapSize = 134217728 {product} {ergonomic}
size_t MaxHeapSize = 402653184 {product} {ergonomic}
| Setting | Heap with --memory 512m |
|---|---|
| Default (25%) | 128 MB |
-XX:MaxRAMPercentage=75 | 384 MB |
-Xmx300m | 300 MB (fixed, ignores the limit) |
How it works:
--entrypoint javareplaces the image'sENTRYPOINT, so the arguments after the image name go tojavainstead of being added tojava -jar app.jar.- 134217728 bytes is 128 MB (25% of 512 MB); 402653184 bytes is 384 MB (75%).
MaxRAMPercentagescales automatically when you change--memory, so the same image fits small and large containers. Leave about 25% for metaspace, threads and other non-heap memory.JAVA_TOOL_OPTIONSis read by every JVM automatically, so you can change JVM flags without editing theENTRYPOINT.
Add a Health Check to the Java Image
A HEALTHCHECK lets Docker test whether the app actually answers, not just whether the process exists.
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
CMD bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /health HTTP/1.0\r\n\r\n" >&3 && grep -q "\"UP\"" <&3'
docker build -t course-server:1.1.0 .
docker run -d --name course -p 8080:8080 course-server:1.1.0
sleep 15
docker ps --format "{{.Names}}: {{.Status}}"
course: Up 15 seconds (healthy)
How it works:
- The check uses only
bashand its built-in/dev/tcpdevice, so no extra tool such ascurlhas to be installed in the image. --start-period=20sgives the JVM time to start before failed checks count.- After 3 failed checks in a row, the status becomes
(unhealthy). Orchestrators such as Docker Swarm and Composedepends_onconditions use this status.
Real-World Example: Dockerize a Java Application With Docker Compose
Docker Compose describes the whole setup in one file: the image build, ports, environment, memory, restart policy and health check. This is the final layout of the project:
course-server/
├── Dockerfile
├── .dockerignore
├── compose.yaml
├── app.env
├── pom.xml
└── src/main/java/com/gocourse/app/CourseServer.java
# Dockerfile
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /build
COPY pom.xml .
RUN mvn -q dependency:go-offline
COPY src ./src
RUN mvn -q -DskipTests package
FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=build --chown=app:app /build/target/course-server-*.jar app.jar
USER app
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
CMD bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /health HTTP/1.0\r\n\r\n" >&3 && grep -q "\"UP\"" <&3'
ENTRYPOINT ["java", "-jar", "app.jar"]
# compose.yaml
services:
course-server:
build: .
image: course-server:${APP_VERSION:-dev}
ports:
- "8080:8080"
env_file: app.env
mem_limit: 512m
restart: unless-stopped
stop_grace_period: 20s
# app.env
APP_ENV=prod
APP_PORT=8080
APP_VERSION=1.1.0 docker compose up -d --build
sleep 20
docker compose ps --format "table {{.Service}}\t{{.Image}}\t{{.Status}}"
curl -s -w "\n" http://localhost:8080/health
SERVICE IMAGE STATUS
course-server course-server:1.1.0 Up 20 seconds (healthy)
{"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":20}
Roll back by starting the previous tag, which is still on the machine:
APP_VERSION=1.0.0 docker compose up -d --no-build
sleep 3
curl -s -w "\n" http://localhost:8080/health
[+] Running 1/1
✔ Container course-server-course-server-1 Started
{"status":"UP","version":"1.0.0","env":"prod","uptimeSeconds":3}
How it works:
- One command to build and run.
docker compose up -d --buildruns the multi-stage build, tags the image withAPP_VERSION, and starts the container with all options fromcompose.yaml. - Same config pattern as before.
env_file: app.envuses the same file format as the systemd service in Run Java as a Service. Secrets stay out of the image. - Production settings.
mem_limitcaps memory,MaxRAMPercentagesizes the heap to that cap,ExitOnOutOfMemoryErrormakes the JVM exit on OOM, andrestart: unless-stoppedstarts it again.stop_grace_periodgives the shutdown hook up to 20 seconds. - Fast rollback. Every release is a tagged image. Switching
APP_VERSIONand runningup -d --no-buildreplaces the container in seconds: Compose stops the old container with SIGTERM, starts one from the 1.0.0 image, and/healthconfirms the version. - Ready for registries. To use the image on other servers,
docker tag course-server:1.1.0 ghcr.io/gocourse/course-server:1.1.0anddocker pushit, then pull the same tag anywhere.