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.

Share

Contents

What goes into a Java image

A container image is a stack of read-only layers. Each Dockerfile instruction that changes files, such as COPY or RUN, adds one layer on top of the ones before it. A running container is the image plus one thin writable layer of its own.

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:

TechniqueWhat it changesEffort
Multi-stage buildThe JDK, Maven and source code stay out of the final imageLow
JAR built by CIThe image build only packages a JAR that was already built and testedLow
Layered JARLibraries get their own layers, so a code change ships one small layerLow
jlink custom runtimeThe runtime holds only the Java modules the application usesMedium: test for modules loaded at run time
Distroless base imageNo shell or package manager in the imageLow, but debugging is harder
BuildpacksMost of the above, with no DockerfileLow

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:

Dockerfile
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 end up in the final image:

Dockerfile
# 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 COPY lines in the first stage matters. Docker reuses a step from its cache when the files it copied have not changed. Copying pom.xml and downloading dependencies before copying src means a code change does not download all the dependencies again.

The examples use the standard Temurin images, which are based on Ubuntu. Alpine variants (21-jre-alpine) are smaller, but Alpine uses a different C library (musl), which some native libraries do not support. Test your application on Alpine before switching.

Building 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:

Shell
# 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"
Dockerfile
# 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.
  • COPY target/*.jar expects one JAR in target. Spring Boot's Maven plugin leaves the original as .jar.original, so this holds by default. If your build produces more than one JAR, name the one to copy.
  • Tagging the image with the commit id ties every image to the exact source it came from, which a tag such as latest cannot do.

The .dockerignore file shown later leaves out the whole target folder, which suits builds inside Docker. With a JAR built outside, let that one file through instead:

Text
# 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 holds defaults, and each environment supplies its own values at run time, as environment variables or files from a ConfigMap or Secret. That way the image tested in staging is the one that runs in production. Never copy credentials into an image: anyone who can pull it can read every layer. See ConfigMaps and Secrets for Spring Boot for how Spring Boot reads them.

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:

FolderWhat it holdsChanges when
dependenciesReleased librariesYou add or upgrade a library
spring-boot-loaderThe code that starts the applicationYou upgrade Spring Boot
snapshot-dependenciesSNAPSHOT librariesOften, while they are in development
applicationYour classes and resourcesEvery build

Spring Boot records these folders in the JAR by default, so no change to pom.xml is needed. The first stage builds the JAR and extracts the folders; the second copies them in order:

Dockerfile
# 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. A push uploads only that layer, and servers that already have the previous version download only that layer.

To see it, change one line of code, build again and run docker history <image>: only the top layers have a new creation time. The -Djarmode=tools command needs Spring Boot 3.3 or later. On older versions, use java -Djarmode=layertools -jar app.jar extract, and org.springframework.boot.loader.JarLauncher before 3.2.

A custom JRE with jlink

A standard JRE contains every Java module, including ones most applications never use, such as the desktop UI libraries. jlink builds a JRE with only the modules you list, and jdeps works out which modules your code and its libraries use.

To see what the two tools do, take a small application that uses only the HTTP client and java.util.logging. It was chosen because it needs just two modules beyond java.base, so the result is easy to check by eye:

Java
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 which modules it needs:

Shell
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
Output
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) for comparison, and the small one again with compression:

Shell
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
Output
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 (java.desktop) and XML.
  • --compress=zip-6 brings it down to 40 MB by compressing the class files inside the runtime. JDK 21 introduced the zip-0 to zip-9 values; older JDKs took a number from 0 to 2.
  • 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 cannot see them. This program creates an elliptic-curve key pair, the kind of key most HTTPS servers use today:

Java
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());
        }
    }
}
Shell
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
Output
java.base
Failed: EC KeyPairGenerator not available
EC key pair created, public key format X.509
  • jdeps reports only java.base, because the program's classes refer to nothing else.
  • 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 jdk.crypto.ec fixes it. From JDK 22 the EC implementation is part of java.base: the same program on JDK 25 succeeds with java.base alone.

The Dockerfile below puts these steps together for a Spring Boot application. jdeps cannot look inside a Spring Boot JAR directly, because the libraries are nested in it, so the JAR is unpacked first:

Dockerfile
# 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"]
jdeps only finds modules your code refers to directly. Modules loaded at run time are missed, so the application can fail only when it reaches them. The most common one is jdk.crypto.ec on JDK 21 and earlier, as shown above, so the Dockerfile adds it. Others you may need are java.naming (JNDI, some database drivers), jdk.management (metrics) and jdk.zipfs. Run the image through your full test suite before relying on it.

The 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-slim or ubuntu, but not on Alpine. To run on Alpine, use eclipse-temurin:21-jdk-alpine in the first two stages and alpine in the last.

Running as a non-root user

By default, a container runs as root. If an attacker finds a way into the application, they have root inside the container, which makes escaping it easier. Create a user and switch to it before the application starts:

Dockerfile
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 lets the heap use 75% of the container's memory limit instead of the default 25%. The next section shows how the JVM uses the limits, and what the remaining 25% is needed for.

To go further, run the container with a read-only file system: docker run --read-only --tmpfs /tmp myapp. The application can then write only to /tmp, which Spring Boot needs for uploads and the embedded server's working files.

The 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 option, on by default since JDK 10 and 8u191, so the same image behaves differently under different limits.

This program prints what the JVM decided. To try it without a container, -XX:MaxRAM sets the memory the JVM sizes its heap from, and -XX:ActiveProcessorCount sets the processor count. A container's limits have the same effect:

Java
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());
    }
}
Output
$ 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 (Copy and MarkSweepCompact) 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.
  • With 1 GB, the maximum heap is 256 MB: 25% of the memory, the default MaxRAMPercentage. 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.
  • With -XX:MaxRAMPercentage=75, 4 GB gives a 3072 MB heap. This is a common setting for a container that runs a single JVM.
  • With only 200 MB, the heap is 100 MB, or 50%. For very small memory the JVM uses MinRAMPercentage instead, which defaults to 50%.
  • The common ForkJoinPool, used by parallel streams and CompletableFuture, gets one thread fewer than the CPU count, and at least one. GC threads are sized from the same count.

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 OOMKilled with exit code 137, with no Java OutOfMemoryError and no stack trace. If that happens while the heap is well below the limit, lower MaxRAMPercentage to leave more room.

The percentage is taken of the memory the JVM detects, which in a container is the memory limit (docker run -m, or resources.limits.memory in Kubernetes). Without a limit, the JVM sees the whole host: 75% of a 64 GB node is a 48 GB heap. So always set a memory limit when you rely on a percentage.

A fixed -Xmx is the other common choice, and it wins when both are set: with 4 GB of memory, -XX:MaxRAMPercentage=75 -Xmx512m gives a 512 MB heap. The difference is what happens when the limit changes:

-XX:MaxRAMPercentage-Xmx
Heap follows the limitYes: raise the limit and the heap grows, with no change to the imageNo: the limit and -Xmx must be changed together
Exact heap sizeDepends on the limitYes
SuitsOne image run with different limits per environmentServices 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.

Kubernetes passes a pod's CPU request to the container as CPU shares, and its CPU limit as a CPU quota. Since JDK 19 the JVM ignores shares and counts only the quota. A pod with a CPU request but no CPU limit therefore sees every CPU on the node, and sizes its GC threads and common pool for all of them. If you run without CPU limits, set -XX:ActiveProcessorCount to match the request.

To pass these options without changing the ENTRYPOINT, set the JAVA_TOOL_OPTIONS environment variable, for example in the Kubernetes Deployment. Every JVM in the container reads it, and prints a "Picked up JAVA_TOOL_OPTIONS" line at startup, so you can confirm it took effect.

Stopping cleanly: PID 1 and signals

docker stop and Kubernetes stop a container the same way. They send SIGTERM to the container's main process, the one with PID 1, wait for a grace period, then send SIGKILL. The grace period is 10 seconds for docker stop, and 30 seconds by default in Kubernetes (terminationGracePeriodSeconds).

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:

Java
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");
    }
}
Output
$ 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 OOMKilled container, because both end with a SIGKILL.

Whether Java receives SIGTERM at all depends on how the Dockerfile starts it. The exec form, ENTRYPOINT ["java", "-jar", "app.jar"], starts java as PID 1. The shell form, ENTRYPOINT java -jar app.jar, runs the command through /bin/sh -c, which makes the shell PID 1. Docker's documentation notes that the program then does not receive the signals, so Java is killed at the end of the grace period without running its hooks.

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 ..., so that java replaces the shell and becomes PID 1.

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 variant also runs as a non-root user already.

Dockerfile
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 does not work. The :debug-nonroot tag of the same image adds a small shell for when you need one.

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.

Shell
# 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:

XML
<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.

Dockerfile vs Jib vs Buildpacks compares the three in more depth, including a Jib image built without Docker and opened layer by layer.

Keeping the build context small

docker build first sends the whole project folder, the build context, to the Docker engine. A .dockerignore file in the project root leaves out what the build does not need, which makes builds faster and stops files such as local credentials from reaching an image by accident:

Text
# 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/ or mvnw when the build runs inside Docker: the build stage uses them. When CI builds the JAR, use the target rule from Building the JAR outside Docker instead.

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 eclipse-temurin:21-jre, and rebuild regularly to pick up security fixes.
  • 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 ENTRYPOINT, so it receives SIGTERM and shuts down gracefully.
  • Set a memory limit on every container, and size the heap with MaxRAMPercentage or -Xmx, leaving 25% or more for memory outside the heap.
  • Set a CPU limit, or pass -XX:ActiveProcessorCount, so the JVM sizes its threads for the CPUs it really gets.
  • 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 .dockerignore, so local files such as .env never reach an image.
  • Scan images for known vulnerabilities in CI before they are pushed, with a scanner such as Trivy or Docker Scout.

Which approach to choose

ApproachWhat it removesGood for
Multi-stage buildThe JDK, Maven and source codeBuilds that happen inside Docker
JAR built by CIThe build tools, from the image build entirelyPipelines that already build and test the JAR
Layered JARNothing; makes rebuilds and pushes fasterApplications you deploy often
DistrolessThe shell and OS toolsProduction, when you rarely need a shell
jlink custom JREJava modules the application does not useThe smallest image, if you test it well
BuildpacksMost of the above, without a DockerfileTeams that want good defaults with no upkeep
MaxRAMPercentage and CPU settingsNothing; sizes the JVM to the containerEvery image: set them deliberately
Exec-form ENTRYPOINTNothing; lets Java receive SIGTERMEvery image

Sizes depend on your application and libraries, so measure your own with docker images rather than relying on published numbers. As a rule, a multi-stage build is the biggest single saving, and the other techniques each take off a smaller amount.

Related pages: deploying Spring Boot on Kubernetes, Kubernetes probes and graceful shutdown, and JVM tuning.