Skip to content
javahacks.dev
DevOps

How to Build a Small Docker Image for a Java Application

Shrink a Java Docker image in six steps: drop the JDK, build in a stage, layer the Spring Boot jar, choose the base, trim dependencies and run non-root.

7 min read
Summarize in AI
Flat illustration of a dependency tree and build phases, with the Docker, OpenJDK and Jenkins logos.

A Java image that weighs 900 MB for a service whose own code is 3 MB is not a mystery. It is a JDK, a Maven cache, the source tree, a fat jar and an operating system, all shipped to production because the Dockerfile took the shortest path. Each of those has a cheap fix, and the fixes stack. This post removes them one at a time and tells you how to measure each, so you stop at the point where the next step costs more than it saves.

Size matters for three practical reasons: pull time when a node starts a new pod, registry storage and transfer cost, and the amount of software an attacker can use if the container is compromised. It does not matter for runtime speed, which depends on the JVM and not on the image. The Dockerfiles target Java 25 and Spring Boot 4, and nothing in them depends on those versions except the image tags.

Start by looking

Do not guess what is big. Ask Docker, layer by layer:

Shell
docker build -t shop:naive .
docker images shop:naive
docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' shop:naive | head -12

docker history lists each layer with its size and the instruction that made it. Two patterns appear in almost every naive Java image: a single layer of several hundred megabytes from FROM the JDK image, and a layer from COPY or RUN mvn that holds the build output and sometimes the dependency cache. For a drill-down with file-level detail, the dive tool shows what each layer added. Write down the starting size so the later steps have a baseline.

Step 1: do not ship the JDK

The JDK includes the compiler, jar, jlink, jshell and the other development tools. The application needs the runtime. Switching the final stage to a JRE image removes tooling the process never uses:

Dockerfile
FROM eclipse-temurin:25-jdk       # builds and runs: large
FROM eclipse-temurin:25-jre       # runs only: smaller

One trade-off to decide on purpose: a JRE has no jcmd, jstack or jmap. Production diagnosis often wants them, see using jcmd, jstack and jmap safely. Many teams keep the JDK image for a debug tag and ship the JRE in the normal one, or attach an ephemeral debug container with the tools to a running pod.

Step 2: build in a separate stage

The Maven or Gradle build needs the JDK, the build tool and a dependency cache of hundreds of megabytes. None of it belongs at runtime. Use two stages and copy across only the jar. The full treatment, with layer ordering and BuildKit cache mounts, is in multi-stage Docker builds for Java. The core shape:

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"]

After this step the image holds a JRE, an operating system and one jar. In most projects this is where the largest drop occurs, because the build stage's contents no longer ship.

Step 3: layer the Spring Boot jar

A Spring Boot fat jar is one file that contains both your code (small, changes every commit) and its libraries (large, change rarely). Copied as a single layer, every deploy pushes and pulls the whole thing. Extract the jar into layers so the libraries are cached:

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

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

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

The order puts the most stable content first. When only your code changes, the first three COPY layers hit the cache on the build machine and in the registry, and the push uploads one small layer. This step does not shrink the image; it shrinks every deploy after the first, which is the number operators feel. Spring Boot 3.3 and later spell the command -Djarmode=tools ... extract --layers; older versions used -Djarmode=layertools ... extract.

Step 4: choose the base

The base image sets the floor. Rough ordering from largest to smallest, each with a cost:

BaseTypical tagTrade-off
Full Debian or Ubuntu JREeclipse-temurin:25-jreFamiliar, has a shell and package manager, largest
Alpine JREeclipse-temurin:25-jre-alpineMuch smaller; uses musl libc, which differs from glibc in DNS and some native libraries
Distroless Javagcr.io/distroless/java* imagesNo shell and no package manager; smallest attack surface; harder to debug
jlink runtime on a slim basebuilt in a stageSmallest JVM, you choose the modules; see slimming with jlink

Two warnings. Alpine's musl libc is a real compatibility difference, not a rumor: native libraries built for glibc, such as some compression, font and database drivers, can fail to load, and DNS resolution behavior differs from glibc's in details that matter for Kubernetes service names. Test your service on the Alpine image under load before committing. And a distroless image has no shell, so docker exec -it ... sh fails by design; plan for debugging with an ephemeral container.

Step 5: trim the dependencies

The jar is the other big contributor. Look at what is inside it:

Shell
unzip -l target/shop.jar | sort -k1 -n -r | head -15

The largest entries are libraries, and some of them nobody calls. Candidates for removal: a second JSON library pulled in by a transitive dependency, a database driver for a database you do not use, a test or tooling library with compile scope, a cloud SDK imported for one class. The dependency tree finds them:

Shell
mvn dependency:tree -Dverbose | grep -E "aws-java-sdk|jackson|httpclient" | head

Use <exclusions> for a transitive library you do not need, and move test-only libraries to <scope>test</scope>. Do this after the earlier steps, not before: it is the most work for the smallest gain per hour.

Step 6: non-root user and a read-only file system

These do not make the image smaller, but they belong in any image that ships. Create a user, switch to it and write only to a temp directory:

Dockerfile
FROM eclipse-temurin:25-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=extract --chown=app:app /layers/out/dependencies/ ./
COPY --from=extract --chown=app:app /layers/out/application/ ./
USER app
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
ENTRYPOINT ["java", "-jar", "app.jar"]

Pair that with readOnlyRootFilesystem: true in the pod spec and a writable emptyDir mounted at /tmp. The heap setting here matters for containers: see setting JVM options in Docker. The complete checklist of image decisions is in writing a Java Dockerfile the right way.

Native images

A GraalVM native image removes the JVM entirely: the final image holds one executable and a minimal base, and starts in milliseconds. The price is a build that takes minutes and needs a lot of memory, restrictions on reflection and dynamic class loading, and a different performance profile at peak load. It is the right answer for functions and scale-to-zero services, and the wrong one for a team that has not hit a startup problem. When a native build fails on reflection, this fix covers the usual case.

What to measure

Keep a small table for the service, filled in as you apply each step:

StepImage sizePull time on a cold nodePush size after a code change
Naive
JRE, two stages
Layered jar
Slim base or jlink

Fill it from docker images, from timing docker pull on a node with no cache, and from the registry's report of uploaded bytes. The last column usually surprises people: layering shrinks the weekly cost far more than choosing a smaller base.

Where this does not apply

If a platform builds your image, such as Spring Boot's bootBuildImage with Cloud Native Buildpacks, or Jib, it already makes the layering choices above, and the useful work is configuring them. If the service runs on a VM and not in a container, none of this applies. Size is also a poor target when it costs you the ability to debug an incident at 3 a.m. The Docker guidance is in the best practices documentation, and the Spring Boot layering feature is documented under container images.

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.