Skip to content
javahacks.dev
DevOps

How to Use Multi Stage Docker Builds for Java Applications

Use multi-stage Docker builds to compile a Java application in a JDK stage and ship only the jar in a JRE stage, with caching for Maven and Gradle.

7 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the Docker, OpenJDK, Kubernetes and Terraform logos.

Before multi-stage builds, a Java team had two bad options. Build the jar on the host and COPY it in, and the image depends on whatever JDK and settings the build machine happened to have. Or build inside the image, and ship the compiler, the Maven cache, the sources and several hundred megabytes of tooling to production, where none of it runs. Multi-stage builds remove the choice. One Dockerfile compiles in a fat JDK stage and ships from a thin runtime stage, and the final image contains only what you copy across.

This post builds a small Spring Boot service image from a single Dockerfile, adds layer ordering and BuildKit cache mounts so rebuilds take seconds, shows the Gradle version, and covers the mistakes that make a multi-stage build slower than the single-stage one it replaced. The Dockerfiles target Java 25 and the eclipse-temurin images; swap the tag for the JDK your project uses.

The pattern

Dockerfile
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY . .
RUN ./mvnw -q -DskipTests package

FROM eclipse-temurin:25-jre
COPY --from=build /src/target/shop.jar /app/shop.jar
ENTRYPOINT ["java", "-jar", "/app/shop.jar"]

Every FROM begins a new stage with its own filesystem. The first is named build with AS build. It holds the JDK, the Maven wrapper and the sources, and it produces target/shop.jar. The second starts from a clean JRE image and pulls exactly one file out of the first with COPY --from=build. Nothing else crosses: not /src, not ~/.m2, not the JDK.

Build and compare what you ship with what you built:

Shell
docker build -t shop:1.0 .
docker images shop:1.0
docker history shop:1.0

docker history lists the layers of the final stage only, and none of them is a compile step. Run docker build --target build -t shop:build . and the same Dockerfile gives you the fat stage, which is handy when you want to run the compile step by itself.

Cache dependencies by ordering layers

The version above copies the whole project before building, so a one-line change to a controller invalidates the COPY . . layer and the next build downloads every dependency again. Docker caches each instruction as a layer and reuses it until the instruction, or the files it copies, change. Put the slow-changing inputs first:

Dockerfile
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src

# 1. Build descriptors only. This layer changes when dependencies change.
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline

# 2. Sources. This layer changes on every commit.
COPY src/ src/
RUN ./mvnw -q -DskipTests package

FROM eclipse-temurin:25-jre
COPY --from=build /src/target/shop.jar /app/shop.jar
ENTRYPOINT ["java", "-jar", "/app/shop.jar"]

The dependency:go-offline layer is rebuilt only when pom.xml or the wrapper files change. A source edit reuses it and re-runs only package. One caveat: go-offline does not resolve everything in every project, because some plugins fetch artifacts at the moment they execute. If package still downloads things, that is why. The next section fixes it properly.

BuildKit cache mounts

A cache mount keeps a directory between builds on the build host without storing it in any layer:

Dockerfile
# syntax=docker/dockerfile:1
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY . .
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q -DskipTests package

/root/.m2 persists across builds, so even a changed pom.xml reuses every artifact it already downloaded, and plugin downloads are covered too. The layer stays small because the cache is never written into it. BuildKit is the default builder in current Docker. In CI, a cache mount lives on the runner, so an ephemeral runner starts cold on every job. Export the cache to a registry or the CI cache instead:

Shell
docker buildx build \
  --cache-from type=registry,ref=registry.example.com/shop:buildcache \
  --cache-to   type=registry,ref=registry.example.com/shop:buildcache,mode=max \
  -t registry.example.com/shop:1.0 --push .

The push side of this pipeline is described in building and pushing Java images in CI.

Gradle

The same shape works for Gradle. The cache directory is /home/gradle/.gradle when you build in the gradle image, or /root/.gradle with a JDK image:

Dockerfile
# syntax=docker/dockerfile:1
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY gradlew settings.gradle.kts build.gradle.kts ./
COPY gradle/ gradle/
RUN --mount=type=cache,target=/root/.gradle ./gradlew --no-daemon dependencies > /dev/null
COPY src/ src/
RUN --mount=type=cache,target=/root/.gradle ./gradlew --no-daemon bootJar -x test

FROM eclipse-temurin:25-jre
COPY --from=build /src/build/libs/shop.jar /app/shop.jar
ENTRYPOINT ["java", "-jar", "/app/shop.jar"]

--no-daemon matters in a build container: a Gradle daemon would linger for a process that exits after one build. If the jar name carries a version, set archiveFileName in the build script, or the COPY --from line has to guess it.

Run the tests in the image build, or not?

You have a choice, and the right answer depends on where your CI already runs tests. Running ./mvnw verify inside the build stage makes the image build fail on a red test, which is attractive, but it also means every image build runs the suite, tests that need a database cannot reach one inside docker build, and test reports are trapped in a throwaway layer. Our default is to run tests in a separate CI step on the checked-out code, then build the image with -DskipTests from the same commit. The image build proves the code packages; the pipeline step proves it works. If you do want tests in the Dockerfile, make them a stage so they can be skipped:

Dockerfile
FROM build AS test
RUN ./mvnw -q test

FROM eclipse-temurin:25-jre AS runtime
COPY --from=build /src/target/shop.jar /app/shop.jar
ENTRYPOINT ["java", "-jar", "/app/shop.jar"]

docker build --target runtime skips the test stage, because nothing in runtime depends on it. BuildKit builds only the stages the target needs, which is also faster than the classic builder.

More than two stages

Two is the minimum and not the maximum. A third stage is useful when you slim the runtime with jlink, see shrinking the JRE with jlink, or extract Spring Boot's layers for better cache reuse:

Dockerfile
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY . .
RUN ./mvnw -q -DskipTests package

FROM eclipse-temurin:25-jdk AS layers
WORKDIR /layers
COPY --from=build /src/target/shop.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination extracted

FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=layers /layers/extracted/dependencies/ ./
COPY --from=layers /layers/extracted/spring-boot-loader/ ./
COPY --from=layers /layers/extracted/snapshot-dependencies/ ./
COPY --from=layers /layers/extracted/application/ ./
ENTRYPOINT ["java", "-jar", "app.jar"]

The dependencies layer changes rarely, so a new image push uploads only the small application layer. For a service with 90 MB of dependencies and a 1 MB application, that is the difference between pushing the whole image on each deploy and pushing a megabyte.

What to watch for

  • **A .dockerignore.** Without target/, .git/ and node_modules/ in it, COPY . . sends hundreds of megabytes to the builder and busts the cache whenever any of them changes.
  • Copy order. If COPY . . precedes the dependency step, nothing is cached. This is the most common mistake.
  • Root in the final stage. Add USER in the runtime stage, see writing a Java Dockerfile the right way.
  • **A JRE image for a program that needs jcmd.** Production diagnosis often wants the JDK tools, so decide before you cut the image down, not during an incident.
  • Image size is not the goal. A 90 MB smaller image saves seconds of pull time; a build that finishes in 40 seconds instead of 6 minutes saves your team's day. Optimize the second first. More size tricks are in building small Java images.

Where this does not apply

If a platform builds the image for you, such as Spring Boot's bootBuildImage or a Jib plugin, there is no Dockerfile and no stages to manage; those tools make the layering decisions above for you. For a project built by a pipeline that already produces a verified jar, copying that jar into a runtime-only Dockerfile is simpler and guarantees you ship the artifact that was tested. The reference for the syntax is the multi-stage builds documentation, and cache options are in Optimize cache usage in builds.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.