How to Write a Dockerfile for Java Apps the Right Way
Write a Dockerfile for a Java service with a multi-stage build, dependency caching, a non-root user, container-aware memory settings and a health check.

A working Dockerfile for a Java service takes five lines. A good one takes about twenty, and each added line answers a failure that someone hit in production: slow builds, jars that never receive SIGTERM, processes killed by memory limits, images that run as root. This post builds the Dockerfile up and explains each decision. The next steps, making it small and using multi-stage builds, refine it.
The result first
# syntax=docker/dockerfile:1
FROM eclipse-temurin:25-jdk AS build
WORKDIR /workspace
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline
COPY src/ src/
RUN ./mvnw -q -DskipTests package \
&& java -Djarmode=tools -jar target/*.jar extract --layers --destination extracted
FROM eclipse-temurin:25-jre
WORKDIR /app
RUN useradd --system --uid 10001 app
COPY --from=build /workspace/extracted/dependencies/ ./
COPY --from=build /workspace/extracted/spring-boot-loader/ ./
COPY --from=build /workspace/extracted/snapshot-dependencies/ ./
COPY --from=build /workspace/extracted/application/ ./
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=65", "-jar", "shop.jar"]The jar name after extract follows your artifact, so adjust shop.jar; set <finalName>shop</finalName> in the POM to make it fixed. If the Spring Boot version you use predates the tools jar mode, the equivalent was -Djarmode=layertools with extract. Check the container images chapter of the reference for your version.
Cache the dependencies
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline
COPY src/ src/Docker rebuilds a layer when its inputs change, and every later layer too. If you copied src first, any code edit would invalidate the layer that downloads dependencies. With this order, the download runs only when pom.xml changes. In CI use BuildKit cache mounts for even better results: RUN --mount=type=cache,target=/root/.m2 ./mvnw package.
Run as a normal user
RUN useradd --system --uid 10001 app
USER appA container process running as root can write anywhere in the container and, with misconfiguration, on the host. A fixed numeric uid works with Kubernetes policies that require a non-root user. Make sure directories the app writes to (logs, /tmp) are writable by it.
Start the JVM correctly
The exec form (a JSON array) makes java the main process. The shell form (ENTRYPOINT java -jar app.jar) wraps it in sh -c, so SIGTERM goes to the shell, and the JVM may be killed by SIGKILL after the grace period without running shutdown hooks or Spring's graceful shutdown. If you need environment variable expansion in options, use JAVA_TOOL_OPTIONS or write a small entrypoint script that ends with exec java ....
Memory:
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=65", "-jar", "shop.jar"]MaxRAMPercentage follows the container's memory limit, unlike a fixed -Xmx. Leave room for non-heap memory, as explained in JVM memory areas, and see what happens when it is wrong in OOMKilled.
Pin the base image
eclipse-temurin:25-jre follows the 25 line and moves with updates. For reproducible builds, pin a digest (eclipse-temurin:25-jre@sha256:...) and update it deliberately with a tool like Dependabot or Renovate. Never use latest.
.dockerignore
target/
.git/
.idea/
*.iml
.envKeeping target/ and .git/ out of the build context speeds the build and prevents local build output and secrets from leaking into layers. A .env file with credentials copied by COPY . . ends up in the image history.
Health check
For plain Docker (not Kubernetes, which has its own probes), a health check lets the orchestrator know the service works:
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s \
CMD wget -q --spider http://localhost:8080/actuator/health || exit 1Install wget or curl in the image, or skip the instruction and use the platform's probes. Give a generous start-period for the JVM.
Secrets
Never COPY credentials or pass them as ARG values that stay in the history. Inject them at runtime through environment variables or mounted secrets. BuildKit's --mount=type=secret supplies build-time secrets without leaving them in layers.
Common mistakes
COPY . .before dependency resolution.- A shell-form
ENTRYPOINT. - A JDK in the final image.
- A fixed
-Xmxlarger than the container limit (Could not reserve enough space for object heap). - Building the jar on the host and copying it, so CI and laptops produce different images.
An entrypoint script for the cases the exec form cannot cover
The exec form is right until you need to compute something at startup: a heap size from a variable, an extra flag in one environment, a file that must exist. Put that logic in a small script and finish it with exec, so the JVM replaces the shell and still receives signals:
#!/bin/sh
set -eu
JAVA_OPTS="${JAVA_OPTS:--XX:MaxRAMPercentage=65}"
if [ -n "${DB_PASSWORD_FILE:-}" ]; then
export SPRING_DATASOURCE_PASSWORD="$(cat "$DB_PASSWORD_FILE")"
fi
exec java $JAVA_OPTS -jar /app/shop.jar "$@"COPY --chmod=0755 entrypoint.sh /app/entrypoint.sh
ENTRYPOINT ["/app/entrypoint.sh"]Without the exec, the shell stays as process 1 and the JVM is its child, which is exactly the signal problem the exec form avoids. The $JAVA_OPTS expansion is unquoted on purpose so that several flags split into separate arguments, and that is also why a value containing spaces needs care. Reading a secret from a mounted file keeps it out of the image and out of docker inspect output.
Let the application shut down gracefully
SIGTERM reaching the JVM is half of a clean stop. The other half is that the application drains in-flight requests before it exits, and Spring Boot does that when you ask:
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 25sThe container runtime then has to wait at least that long. Docker's default is 10 seconds before SIGKILL, so give it room, and make the Kubernetes terminationGracePeriodSeconds a few seconds larger than the phase timeout:
docker run --name shop --stop-timeout 30 -p 8080:8080 shop:1.0
docker stop shopVerify the image instead of trusting it
Four checks take under a minute, and each catches one of the mistakes above:
docker build -t shop:1.0 .
docker run -d --name shop --memory 512m -p 8080:8080 shop:1.0
docker exec shop id
docker exec shop sh -c 'ps -o pid,user,args -p 1'
docker inspect shop --format '{{.HostConfig.Memory}}'
time docker stop shopid should show the numeric user you created and not root. ps should show java as process 1 (or entrypoint.sh only until the exec), and if it shows sh -c java ... you have the shell form. The inspect call confirms the memory limit the JVM will read. And docker stop should return in a second or two, because a stop that takes the full ten seconds means the JVM never saw the signal and was killed.
The Gradle variant
The same layering idea works with Gradle. Only the wrapper and the dependency step change:
FROM eclipse-temurin:25-jdk AS build
WORKDIR /workspace
COPY gradlew settings.gradle.kts build.gradle.kts ./
COPY gradle/ gradle/
RUN ./gradlew --no-daemon dependencies > /dev/null
COPY src/ src/
RUN ./gradlew --no-daemon bootJar -x testThe dependencies task resolves and downloads the dependency graph without compiling anything, so the layer is reused until a build file changes. Skipping tests inside the image build is a choice: run them in CI before the build, so a failed test stops the pipeline early and the image only contains code that passed.
A cache mount for repeat builds
If the CI runner keeps BuildKit's cache, a cache mount avoids downloading every artifact on every build even when pom.xml changed:
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q -DskipTests packageThe cache lives outside the image, so it never grows the layers. It is a speed-up and not a correctness feature: a build must still succeed from an empty cache, and a clean build on a fresh runner proves that.
Where this does not apply
If you use Spring Boot's buildpacks (spring-boot:build-image) or Jib, they produce a similar image without a Dockerfile and apply these practices for you. The Dockerfile reference and the Spring Boot Dockerfile guide are the primary sources, and the image that will not start is covered in troubleshooting a Spring Boot image.


