Docker Multi-Stage Builds for Java: Minimal JRE Images
A Java image built the obvious way carries a full JDK, Maven and your source code into production, none of which the application needs to run. This article shows how to ship only what it does need: a multi-stage build or a JAR built by CI, a custom JRE made with jlink, layers that make rebuilds fast, a non-root user, and two alternatives that need no Dockerfile tuning at all. It also shows, with programs you can run, how the JVM sizes itself inside a container and how to make sure it shuts down cleanly.
Contents
What goes into a Java image The starting point: a single-stage Dockerfile Multi-stage build Building the JAR outside Docker Layer caching: rebuild only what changed A custom JRE with jlink Running as a non-root user The JVM inside a container Stopping cleanly: PID 1 and signals Distroless base images No Dockerfile: Spring Boot Buildpacks Keeping the build context small Production checklist Which approach to choose
What goes into a Java image
A container image is a stack of read-only layers. Each Dockerfile instruction that changes files, such as COPYRUN
Layers are what make images cheap to rebuild and ship. Docker reuses a cached layer when its instruction and inputs have not changed, and a registry stores each layer once, however many images share it. A push or pull transfers only the layers the other side does not already have.
At run time, a Java application needs three things: a Java runtime, the application's classes and libraries, and the operating system libraries the runtime links against. Anything else in the image is weight to push, pull and scan for vulnerabilities. Each technique on this page removes one kind of weight, or makes the weight that remains cheaper to ship:
| Technique | What it changes | Effort |
|---|---|---|
| Multi-stage build | The JDK, Maven and source code stay out of the final image | Low |
| JAR built by CI | The image build only packages a JAR that was already built and tested | Low |
| Layered JAR | Libraries get their own layers, so a code change ships one small layer | Low |
| jlink custom runtime | The runtime holds only the Java modules the application uses | Medium: test for modules loaded at run time |
| Distroless base image | No shell or package manager in the image | Low, but debugging is harder |
| Buildpacks | Most of the above, with no Dockerfile | Low |
Two things matter as much as the image itself: how the JVM sizes its heap and threads inside the container's limits, and whether the Java process receives the signal that stops the container. Both have their own sections below, with programs that show the effect.
The starting point: a single-stage Dockerfile
This is how most Java Dockerfiles start. It copies the whole project into a JDK image, builds it there, and runs the result:
FROM eclipse-temurin:21-jdk
WORKDIR /app
COPY . .
RUN ./mvnw package -DskipTests
EXPOSE 8080
CMD ["java", "-jar", "target/app.jar"]
It works, but everything used to build the application stays in the image: the full JDK (compiler and tools included), the Maven repository with every build and test dependency, and your source code. None of it is needed to run the application. It makes the image several times larger than it needs to be, slower to push and pull, and gives an attacker who gets into the container more tools to use.
Multi-stage build
A multi-stage build uses one image to build the application and a second, smaller one to run it. Only the files you copy across with COPY --from
# Stage 1: build the JAR
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /app
# Download dependencies first. This layer is reused until pom.xml changes.
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw dependency:go-offline -q
COPY src src
RUN ./mvnw package -DskipTests -q
# Stage 2: run it on a JRE, without Maven or the source code
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
The order of the COPYpom.xmlsrc
21-jre-alpineBuilding the JAR outside Docker
The builds above compile the application inside Docker. In most production pipelines, the CI system has already built and tested the JAR by the time an image is made: Maven or Gradle runs there with its own dependency cache, and the tests run once. The Dockerfile then only has to package that JAR on a JRE image:
# In the CI pipeline: build and test once, then package the tested JAR
./mvnw -B verify
docker build -t registry.example.com/payment-service:"$GIT_COMMIT" .
docker push registry.example.com/payment-service:"$GIT_COMMIT"
# target/*.jar was built and tested by the CI pipeline before docker build ran
FROM eclipse-temurin:21-jre AS extract
WORKDIR /app
COPY target/*.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted
FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=extract /app/extracted/dependencies/ ./
COPY --from=extract /app/extracted/spring-boot-loader/ ./
COPY --from=extract /app/extracted/snapshot-dependencies/ ./
COPY --from=extract /app/extracted/application/ ./
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "org.springframework.boot.loader.launch.JarLauncher"]
- No JDK, Maven or source code is involved in the image build at all. The first stage uses a JRE, which is enough to split the JAR into its layers, and the final image is the same as in the layer caching section.
- The image contains exactly the JAR the tests ran against. Building again inside Docker would produce a second JAR that was never tested itself.
expects one JAR inCOPY target/*.jar . Spring Boot's Maven plugin leaves the original astarget , so this holds by default. If your build produces more than one JAR, name the one to copy..jar.original- Tagging the image with the commit id ties every image to the exact source it came from, which a tag such as
cannot do.latest
The .dockerignoretarget
# Send only the JAR from target/ to the build
target/*
!target/*.jar
Configuration stays out of the image either way. The JAR's application.yml
Building inside Docker, as in the earlier sections, still has a place. It needs nothing on the build machine except Docker, and every developer and CI runner builds with the same JDK and Maven versions. Choose it when you have no CI pipeline that builds the JAR, or when you want the Dockerfile alone to describe the whole build.
Layer caching: rebuild only what changed
Docker builds an image as a stack of layers, one per instruction. When you build again, it reuses every layer whose inputs did not change. When you push or pull, it skips layers the other side already has.
A Spring Boot JAR works against this. Your own code and all of your libraries sit inside one file, so changing a single line changes the whole JAR. Docker then rebuilds, pushes and pulls every library again, even though none of them changed.
The fix is to split the JAR into four folders, grouped by how often they change, and copy each one in its own step, the least changing first:
| Folder | What it holds | Changes when |
|---|---|---|
dependencies | Released libraries | You add or upgrade a library |
spring-boot-loader | The code that starts the application | You upgrade Spring Boot |
snapshot-dependencies | SNAPSHOT libraries | Often, while they are in development |
application | Your classes and resources | Every build |
Spring Boot records these folders in the JAR by default, so no change to pom.xml
# Build the JAR and split it into its four folders
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /app
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw dependency:go-offline -q
COPY src src
RUN ./mvnw package -DskipTests -q
RUN java -Djarmode=tools -jar target/*.jar extract --layers --launcher --destination extracted
# Copy the folders, least changing first
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=builder /app/extracted/dependencies/ ./
COPY --from=builder /app/extracted/spring-boot-loader/ ./
COPY --from=builder /app/extracted/snapshot-dependencies/ ./
COPY --from=builder /app/extracted/application/ ./
EXPOSE 8080
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
Now, when only your code changed, Docker reuses the first three folders from its cache and rebuilds only application
docker history <image>-Djarmode=toolsjava -Djarmode=layertools -jar app.jar extractorg.springframework.boot.loader.JarLauncherA custom JRE with jlink
A standard JRE contains every Java module, including ones most applications never use, such as the desktop UI libraries. jlinkjdeps
To see what the two tools do, take a small application that uses only the HTTP client and java.util.loggingjava.base
package com.example;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.util.logging.Logger;
public class PriceCheck {
private static final Logger LOG = Logger.getLogger(PriceCheck.class.getName());
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/")).build();
HttpClient client = HttpClient.newHttpClient();
LOG.info("Built " + request.method() + " " + request.uri() + " with " + client.version());
}
}
Compile it, package it, and ask jdeps
javac -d classes src/com/example/PriceCheck.java
jar --create --file app.jar --main-class com.example.PriceCheck -C classes .
jdeps --print-module-deps app.jar
java.base,java.logging,java.net.http
Now build three runtimes and compare their sizes: one with only those modules, one with the whole Java SE platform (java.se
jlink --add-modules java.logging,java.net.http \
--strip-debug --no-man-pages --no-header-files --output jre-min
jlink --add-modules java.se \
--strip-debug --no-man-pages --no-header-files --output jre-se
jlink --add-modules java.logging,java.net.http --compress=zip-6 \
--strip-debug --no-man-pages --no-header-files --output jre-min-zip
du -sh jre-min jre-se jre-min-zip
jre-min/bin/java -jar app.jar
54M jre-min
90M jre-se
40M jre-min-zip
Nov 14, 2026 7:18:32 PM com.example.PriceCheck main
INFO: Built GET https://example.com/ with HTTP_2
- The runtime with three modules is 54 MB, against 90 MB for the full Java SE platform. The saving comes from modules this application never touches, such as the desktop UI (
) and XML.java.desktop brings it down to 40 MB by compressing the class files inside the runtime. JDK 21 introduced the--compress=zip-6 tozip-0 values; older JDKs took a number from 0 to 2.zip-9- The last two lines show the application running on the small runtime. The first of them is the log record's date and time, so it differs on every run.
These sizes were measured with OpenJDK 21.0.12 on Linux x64. Your numbers depend on the modules your libraries pull in, and a Spring Boot application usually needs a longer list.
The trap is a module that is loaded only at run time. Cryptography providers are found that way, so jdeps
package com.example;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class EcKeyCheck {
public static void main(String[] args) {
try {
KeyPair keys = KeyPairGenerator.getInstance("EC").generateKeyPair();
System.out.println("EC key pair created, public key format "
+ keys.getPublic().getFormat());
} catch (NoSuchAlgorithmException e) {
System.out.println("Failed: " + e.getMessage());
}
}
}
jdeps --print-module-deps ec.jar
jlink --add-modules java.base --output jre-base
jre-base/bin/java -jar ec.jar
jlink --add-modules java.base,jdk.crypto.ec --output jre-ec
jre-ec/bin/java -jar ec.jar
java.base
Failed: EC KeyPairGenerator not available
EC key pair created, public key format X.509
reports onlyjdeps , because the program's classes refer to nothing else.java.base- On a runtime built from that list, the EC algorithm is missing. In a real service the same gap shows up as a failed TLS handshake, often only when the first HTTPS call is made.
- Adding
fixes it. From JDK 22 the EC implementation is part ofjdk.crypto.ec : the same program on JDK 25 succeeds withjava.base alone.java.base
The Dockerfile below puts these steps together for a Spring Boot application. jdeps
# Stage 1: build the JAR
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /app
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw dependency:go-offline -q
COPY src src
RUN ./mvnw package -DskipTests -q
# Stage 2: work out the modules and build a JRE with only those
FROM eclipse-temurin:21-jdk AS jre-builder
WORKDIR /work
COPY --from=builder /app/target/*.jar app.jar
RUN mkdir unpacked && cd unpacked && jar xf ../app.jar
RUN jdeps --ignore-missing-deps --print-module-deps --recursive \
--multi-release 21 \
--class-path 'unpacked/BOOT-INF/lib/*' \
unpacked/BOOT-INF/classes > modules.txt
RUN jlink --add-modules "$(cat modules.txt),jdk.crypto.ec" \
--strip-debug --no-man-pages --no-header-files \
--compress=zip-6 \
--output /custom-jre
# Stage 3: the custom JRE and the application on a plain OS image
FROM debian:12-slim
ENV JAVA_HOME=/opt/java
ENV PATH="${JAVA_HOME}/bin:${PATH}"
COPY --from=jre-builder /custom-jre ${JAVA_HOME}
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
jdepsjdk.crypto.ecjava.namingjdk.managementjdk.zipfsThe JRE must run on the same kind of C library it was built with. One built in the standard Temurin JDK image runs on glibc-based images such as debian:12-slimubuntueclipse-temurin:21-jdk-alpinealpine
Running as a non-root user
By default, a container runs as root
FROM eclipse-temurin:21-jre
WORKDIR /app
# A system user with no password and no login shell
RUN groupadd --system app && useradd --system --gid app --no-create-home app
COPY --from=builder /app/target/*.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
The user only needs to read the JAR, so there is no need to change its owner. Ports below 1024 need root, which is one more reason to keep the default port 8080.
-XX:MaxRAMPercentage=75
docker run --read-only --tmpfs /tmp myapp/tmpThe JVM inside a container
The JVM reads the container's limits when it starts. It treats the memory limit as the machine's memory and the CPU limit as its number of processors. From those numbers it sizes the heap, picks a garbage collector and sizes its thread pools. This is the UseContainerSupport
This program prints what the JVM decided. To try it without a container, -XX:MaxRAM-XX:ActiveProcessorCount
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
public class JvmView {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
String gcs = ManagementFactory.getGarbageCollectorMXBeans().stream()
.map(GarbageCollectorMXBean::getName)
.collect(Collectors.joining(", "));
System.out.printf("CPUs seen : %d%n", rt.availableProcessors());
System.out.printf("Max heap : %d MB%n", rt.maxMemory() / (1024 * 1024));
System.out.printf("Collectors : %s%n", gcs);
System.out.printf("Common pool : %d threads%n", ForkJoinPool.commonPool().getParallelism());
}
}
$ java -XX:MaxRAM=1g -XX:ActiveProcessorCount=1 JvmView
CPUs seen : 1
Max heap : 247 MB
Collectors : Copy, MarkSweepCompact
Common pool : 1 threads
$ java -XX:MaxRAM=1g -XX:ActiveProcessorCount=2 JvmView
CPUs seen : 2
Max heap : 256 MB
Collectors : G1 Young Generation, G1 Concurrent GC, G1 Old Generation
Common pool : 1 threads
$ java -XX:MaxRAM=4g -XX:ActiveProcessorCount=4 -XX:MaxRAMPercentage=75 JvmView
CPUs seen : 4
Max heap : 3072 MB
Collectors : G1 Young Generation, G1 Concurrent GC, G1 Old Generation
Common pool : 3 threads
$ java -XX:MaxRAM=200m -XX:ActiveProcessorCount=2 JvmView
CPUs seen : 2
Max heap : 100 MB
Collectors : G1 Young Generation, G1 Concurrent GC, G1 Old Generation
Common pool : 1 threads
- With one CPU, the JVM picks the Serial collector (
andCopy ) instead of G1. Serial pauses the application for every collection and uses one thread, so a service limited to one CPU can pause longer than it did on a developer laptop.MarkSweepCompact - With 1 GB, the maximum heap is 256 MB: 25% of the memory, the default
. The other 75% stays unused by the heap unless you raise the percentage. The 247 MB in the first run is the Serial collector reporting the heap minus one of its survivor spaces.MaxRAMPercentage - With
, 4 GB gives a 3072 MB heap. This is a common setting for a container that runs a single JVM.-XX:MaxRAMPercentage=75 - With only 200 MB, the heap is 100 MB, or 50%. For very small memory the JVM uses
instead, which defaults to 50%.MinRAMPercentage - The common
, used by parallel streams andForkJoinPool , gets one thread fewer than the CPU count, and at least one. GC threads are sized from the same count.CompletableFuture
The heap is not the only memory the JVM uses. Class metadata (metaspace, unlimited by default), compiled code (a 240 MB code cache is reserved), thread stacks (1 MB reserved per thread on Linux x64), GC bookkeeping and direct buffers all come on top. When the whole process goes over the container's limit, the kernel kills it with SIGKILL. Kubernetes reports this as OOMKilledOutOfMemoryErrorMaxRAMPercentage
The percentage is taken of the memory the JVM detects, which in a container is the memory limit (docker run -mresources.limits.memory
A fixed -Xmx-XX:MaxRAMPercentage=75 -Xmx512m
-XX:MaxRAMPercentage | -Xmx | |
|---|---|---|
| Heap follows the limit | Yes: raise the limit and the heap grows, with no change to the image | No: the limit and -Xmx |
| Exact heap size | Depends on the limit | Yes |
| Suits | One image run with different limits per environment | Services sized individually by hand |
75% suits a typical Spring Boot service. Use 50% to 60% for small containers (512 MB or less), for applications with many threads, and for libraries that use a lot of direct memory, such as Netty, Kafka clients and gRPC. Memory outside the heap is a bigger share of the total in those cases.
-XX:ActiveProcessorCountTo pass these options without changing the ENTRYPOINTJAVA_TOOL_OPTIONS
Stopping cleanly: PID 1 and signals
docker stopdocker stopterminationGracePeriodSeconds
On SIGTERM, the JVM runs its shutdown hooks before it exits, and that is where Spring Boot's graceful shutdown lets in-flight requests finish. On SIGKILL the process ends at once and nothing runs. This program registers a hook and waits, and was stopped once with each signal:
public class GracefulStop {
public static void main(String[] args) throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutdown hook: finishing in-flight work and closing connections");
}));
System.out.println("Started, waiting for requests");
Thread.sleep(60000);
System.out.println("Not reached when the process is stopped");
}
}
$ java GracefulStop & sleep 1; kill -TERM $!; wait $!; echo "exit code $?"
Started, waiting for requests
Shutdown hook: finishing in-flight work and closing connections
exit code 143
$ java GracefulStop & sleep 1; kill -KILL $!; wait $!; echo "exit code $?"
Started, waiting for requests
exit code 137
- SIGTERM ran the hook, and the exit code is 143: 128 plus 15, the number of SIGTERM.
- SIGKILL skipped the hook, and the exit code is 137: 128 plus 9. It is the same code as an
container, because both end with a SIGKILL.OOMKilled
Whether Java receives SIGTERM at all depends on how the Dockerfile starts it. The exec form, ENTRYPOINT ["java", "-jar", "app.jar"]javaENTRYPOINT java -jar app.jar/bin/sh -c
Every example on this page uses the exec form. If you need a shell script to build the command line, end the script with exec java ...java
Distroless base images
Google's distroless images contain the Java runtime and the few system files it needs, and nothing else: no shell, no package manager, no utilities. An attacker who gets in has almost nothing to work with. The nonroot
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /app
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw dependency:go-offline -q
COPY src src
RUN ./mvnw package -DskipTests -q
FROM gcr.io/distroless/java21-debian12:nonroot
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080
# The image's entry point is "java -jar", so only the JAR is given here
CMD ["app.jar"]
The trade-off is debugging: with no shell, docker exec -it ... sh:debug-nonroot
No Dockerfile: Spring Boot Buildpacks
Spring Boot can build an image without a Dockerfile, using Cloud Native Buildpacks. It applies most of this article by itself: a JRE-only image, the layers from the layer caching section, a non-root user, and memory settings worked out from the container's limit when it starts.
# Maven (Docker must be running)
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=myorg/payment-service
# Gradle
./gradlew bootBuildImage --imageName=myorg/payment-service
To set the image name and Java version in the build itself, configure the Maven plugin:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<name>myorg/${project.artifactId}:${project.version}</name>
<env>
<BP_JVM_VERSION>21</BP_JVM_VERSION>
</env>
</image>
</configuration>
</plugin>
Buildpacks are a good default when you have no special requirements. Write a Dockerfile when you need full control over the base image or the steps.
Keeping the build context small
docker build.dockerignore
# Build output: the image builds its own
target/
build/
# Version control and IDE files
.git/
.idea/
*.iml
.vscode/
.DS_Store
# Local files that must never reach an image
.env
*.log
Do not exclude .mvn/mvnwtarget
Production checklist
The practices from this page, in the order an image is built and run:
- Build and test the JAR once in CI, and package that exact JAR. Do not build it again inside Docker.
- Tag each image with the commit id, and deploy by that tag rather than by
.latest - Pin the base image to a specific Java version, such as
, and rebuild regularly to pick up security fixes.eclipse-temurin:21-jre - Use a JRE base image, or a distroless or jlink runtime, never a JDK in the final stage.
- Split Spring Boot JARs into layers, so a code change ships one small layer.
- Run as a non-root user, and keep the application on a port above 1024.
- Start Java with an exec-form
, so it receives SIGTERM and shuts down gracefully.ENTRYPOINT - Set a memory limit on every container, and size the heap with
orMaxRAMPercentage , leaving 25% or more for memory outside the heap.-Xmx - Set a CPU limit, or pass
, so the JVM sizes its threads for the CPUs it really gets.-XX:ActiveProcessorCount - Keep configuration and secrets out of the image: supply them at run time as environment variables or mounted files.
- Keep the build context small with
, so local files such as.dockerignore never reach an image..env - Scan images for known vulnerabilities in CI before they are pushed, with a scanner such as Trivy or Docker Scout.
Which approach to choose
| Approach | What it removes | Good for |
|---|---|---|
| Multi-stage build | The JDK, Maven and source code | Builds that happen inside Docker |
| JAR built by CI | The build tools, from the image build entirely | Pipelines that already build and test the JAR |
| Layered JAR | Nothing; makes rebuilds and pushes faster | Applications you deploy often |
| Distroless | The shell and OS tools | Production, when you rarely need a shell |
| jlink custom JRE | Java modules the application does not use | The smallest image, if you test it well |
| Buildpacks | Most of the above, without a Dockerfile | Teams that want good defaults with no upkeep |
MaxRAMPercentage | Nothing; sizes the JVM to the container | Every image: set them deliberately |
Exec-form ENTRYPOINT | Nothing; lets Java receive SIGTERM | Every image |
Sizes depend on your application and libraries, so measure your own with docker images
Related pages: