Why does copying a Spring Boot fat jar into Docker defeat layer caching?
A typical Dockerfile for a Spring Boot service copies the executable jar onto a JRE base image with a single COPY instruction. That works, but it puts your entire application into one image layer: your own classes, their resources, and every dependency nested inside the jar. Docker identifies layers by a digest of their content. Change one line of a controller, rebuild the jar, and its bytes differ. The layer gets a new digest, and Docker treats it as entirely new.
The consequences repeat at each stage. CI rebuilds and pushes the full layer. The registry stores another copy of it. Every node that runs the new version pulls it again, even though most of its contents, such as the framework, the web server and the database drivers, did not change. Jars are already compressed, so registry compression saves little.
Illustrative estimate. Assume 80 MB of dependencies, 2 MB of application code, 20 releases a month, and 10 nodes that each pull every release.
- Single-layer image: each release pushes about 82 MB and pulls 820 MB in total. Over a month that is about 16 GB of pulls.
- Dependencies in their own layer: each release changes only the 2 MB application layer. Total pulls drop to about 400 MB a month.
The goal is to split the image so that dependencies, which rarely change, sit in lower layers that stay cached. Application code, which changes frequently, goes on top. This matters most for teams with frequent CI builds, metered registry storage or egress, or many deploy targets such as clusters, regions or edge nodes.
How does a Spring Boot layered jar work?
When you build an executable jar with the Spring Boot Maven or Gradle plugin, it writes a layers index file, BOOT-INF/layers.idx, into the archive. The index assigns every entry in the jar to a named layer. Nothing about how the application runs changes; the index only records which files belong together so tooling can split them apart later.
The default layers, ordered from least to most frequently changed, are:
dependencies: third-party jars with release versions. These change only when you bump a dependency.spring-boot-loader: the launcher classes that boot the jar. These change only when you upgrade Spring Boot.snapshot-dependencies: any dependency whose version ends in-SNAPSHOT. These are kept separate because they can change on any build.application: your compiled classes and resources. These change on nearly every commit.
Each layer becomes one directory, and each directory becomes one COPY instruction and therefore one Docker image layer. The order matters because Docker invalidates the cache for a changed layer and for every layer above it. If you put application first, every code change forces Docker to rebuild and push the dependency layer too, which brings back the problem the index is meant to solve.
You can inspect the index with java -Djarmode=layertools -jar app.jar list, which prints the layer names in order, and with the extract command, which writes each layer to its own directory. Newer Spring Boot releases replace this with a tools jarmode, and its extract command uses different arguments and produces a different output layout. Check the documentation for your Spring Boot version before you write the Dockerfile, rather than copying syntax from an older example.
# Stage 1: unpack the layered jar into one directory per layer
FROM eclipse-temurin:17-jre AS builder
WORKDIR /workspace
COPY target/*.jar app.jar
# Optional: print the layer names in the order defined by BOOT-INF/layers.idx
RUN java -Djarmode=layertools -jar app.jar list
# Writes dependencies/, spring-boot-loader/, snapshot-dependencies/, application/
# (layertools syntax; newer releases use the 'tools' jarmode with different
# extract arguments and output layout, so check your version's docs)
RUN java -Djarmode=layertools -jar app.jar extract
# Stage 2: copy layers from least to most frequently changed
FROM eclipse-temurin:17-jre
WORKDIR /app
# Changes only when a release dependency is bumped
COPY --from=builder /workspace/dependencies/ ./
# Changes only when Spring Boot is upgraded
COPY --from=builder /workspace/spring-boot-loader/ ./
# May change on any build, so it sits above the stable layers
COPY --from=builder /workspace/snapshot-dependencies/ ./
# Changes on nearly every commit; a code change rebuilds only this layer
COPY --from=builder /workspace/application/ ./
# Launcher class for Spring Boot 3.2+; older releases use
# org.springframework.boot.loader.JarLauncher
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
A multi-stage Dockerfile that lists and extracts the jar's layers with the layertools jarmode, then copies each layer with its own COPY instruction from least to most frequently changed, so a code-only change invalidates just the final image layer.
How do you write a multi-stage Dockerfile for a Spring Boot layered jar?
The Dockerfile has two stages. The builder starts from a JDK image and copies only pom.xml (or build.gradle and the settings file) before running a dependency-resolution step such as Maven's dependency:go-offline. Docker caches that layer until the build file changes, so editing source code does not trigger a full re-download. Next, copy src, build the jar, and run layer extraction in the same stage. For extra speed, a BuildKit cache mount on ~/.m2 or ~/.gradle keeps the local repository between builds without baking it into any image layer.
The runtime stage starts from a JRE-only image and runs one COPY --from=builder per extracted directory. Follow the order in the jar's layers.idx: dependencies, loader, snapshot dependencies, then application. Docker invalidates every layer after the first one that changes. Putting the most volatile content last means a code change rebuilds and pushes only the small application layer.
Before you write the ENTRYPOINT, list the extracted output. Depending on the Spring Boot version, you get one of two layouts:
- The loader's classes plus your application classes. The entrypoint is a launcher class from
spring-boot-loader, and its package name has changed between releases. - A thin runnable jar next to a
libdirectory. The entrypoint isjava -jaron that jar.
Copying a launcher class name from an older guide often produces a ClassNotFoundException at startup.
Create a non-root user and switch to it with USER, so a compromised process cannot write to system paths. For memory, set -XX:MaxRAMPercentage instead of -Xmx. Modern JVMs read the container's cgroup memory limit, so the heap scales with the limit set in your orchestrator without rebuilding the image.
# syntax=docker/dockerfile:1
# ---- Builder: full JDK, resolves deps, builds, extracts layers ----
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /builder
# Build files first: this layer stays cached until pom.xml changes
COPY mvnw pom.xml ./
COPY .mvn .mvn
# Optional cache mount keeps ~/.m2 between builds, outside any image layer
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offline
# Source changes invalidate only the layers from here down
COPY src src
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B package -DskipTests \
&& cp target/*.jar application.jar
# Boot 3.3+ tools mode; older versions use -Djarmode=layertools and emit
# a different layout. Run `ls -R extracted` and match ENTRYPOINT to it.
RUN java -Djarmode=tools -jar application.jar extract --layers --destination extracted
# ---- Runtime: JRE only, one COPY per layer in layers.idx order ----
FROM eclipse-temurin:21-jre
WORKDIR /application
# Run as an unprivileged system user
RUN groupadd --system spring && useradd --system --gid spring spring
# Least volatile first, application code last
COPY --from=builder /builder/extracted/dependencies/ ./
COPY --from=builder /builder/extracted/spring-boot-loader/ ./
COPY --from=builder /builder/extracted/snapshot-dependencies/ ./
COPY --from=builder /builder/extracted/application/ ./
USER spring:spring
# This layout is a thin runnable jar plus lib/, so plain java -jar works.
# Heap tracks the container memory limit instead of a fixed -Xmx.
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-jar", "application.jar"]
A two-stage Dockerfile that caches Maven dependencies, extracts a Spring Boot 3.3+ layered jar into a runnable jar plus lib layout, copies each layer in index order, and runs as a non-root user with a heap sized as a percentage of the container memory limit.
How can you customize jar layering for internal libraries?
The default layers treat every dependency the same way, but they do not change at the same rate. Third-party libraries such as Spring, Jackson, and database drivers might change a few times a year. Shared internal modules, such as a company security starter, common DTOs, or client SDKs for other teams' services, often change every sprint. When those internal jars sit in the main dependencies layer, one bump to an internal module invalidates that whole layer. Every image then rebuilds and pushes the full third-party dependency set again.
You can fix this by defining a custom layer in the build plugin's layering configuration. In Maven this is a layers XML file referenced from the Spring Boot plugin. In Gradle it is the layered block of bootJar. Match your organization's group ID (for example com.example:*) into a layer such as company-dependencies. Then set the layer order so it sits after dependencies and before application. Inclusion rules are evaluated in order and the first match wins, so put the internal-group rule ahead of the catch-all dependency rule. Extraction creates one directory per layer, so add a matching COPY instruction in the Dockerfile in the same position.
When an internal module changes, only that layer and the application layer above it are rebuilt and pushed. The large third-party layer stays cached on the build agent, in the registry, and on nodes that already pulled it.
This benefit depends on the layers below it actually staying stable. If internal libraries depend on frequently released internal parents, or if a platform BOM bumps third-party versions on every release, the lower layer changes anyway and the ordering gains nothing. SNAPSHOT dependencies change on every build by definition. Keep them in their own layer close to application, and make sure your internal-group rule does not pull them into a lower layer.
// build.gradle (Groovy DSL): custom layer for internal libraries
tasks.named("bootJar") {
layered {
application {
intoLayer("spring-boot-loader") {
include "org/springframework/boot/loader/**"
}
intoLayer("application")
}
dependencies {
// First match wins, so the most specific rules go first.
// Snapshots change on every build: keep them in their own
// layer, even when they are internal modules.
intoLayer("snapshot-dependencies") {
include "*:*:*SNAPSHOT"
}
// Internal company libraries that change every sprint.
intoLayer("company-dependencies") {
include "com.example:*:*"
}
// Catch-all: stable third-party jars (Spring, Jackson, drivers).
intoLayer("dependencies")
}
// Least to most frequently changing, bottom to top of the image.
layerOrder = ["dependencies", "spring-boot-loader",
"company-dependencies", "snapshot-dependencies",
"application"]
}
}
// Dockerfile: one COPY per extracted layer, in the same order, e.g.
// COPY --from=builder /build/extracted/dependencies/ ./
// COPY --from=builder /build/extracted/spring-boot-loader/ ./
// COPY --from=builder /build/extracted/company-dependencies/ ./
// COPY --from=builder /build/extracted/snapshot-dependencies/ ./
// COPY --from=builder /build/extracted/application/ ./
A Gradle bootJar layered configuration that puts com.example internal libraries in a company-dependencies layer between third-party dependencies and application code, with snapshots isolated above it, plus the matching Dockerfile COPY order.
Should you use jlink to shrink the Spring Boot runtime?
jlink can cut the runtime layer down, but treat it as an experiment to measure. Unlike the dependency layers, the JRE layer changes rarely, so a smaller one mostly saves registry storage and cold-pull time on fresh nodes. It does little for rebuild speed.
In the builder stage, extract the layered jar and run jdeps against your application classes with the dependency directory on the class path. Use --multi-release set to your target Java version so it resolves the correct classes inside multi-release jars. Add --ignore-missing-deps so optional dependencies that are not on the class path don't abort the analysis. Add --print-module-deps to get a comma-separated module list. Pass that list to jlink --add-modules, typically with --strip-debug, --no-header-files and --no-man-pages. Then copy the output directory onto a minimal base image in the final stage.
The weak point is the module list. jdeps only sees static references. Code loaded reflectively or through ServiceLoader doesn't show up. Common gaps are java.naming (JNDI), java.sql, jdk.crypto.ec (TLS handshakes fail without it), jdk.charsets and jdk.localedata. These failures appear at runtime, often only on a specific code path. Keep the module list explicit in version control and add to it deliberately. Gate every change on a full integration test run, not just a startup check.
You also take on JDK patching. A vendor base image picks up security fixes when you rebuild. A custom runtime only gets them when you update the builder JDK and run jlink again.
Finally, minimal and distroless-style bases have no shell, package manager or debugging tools, so docker exec troubleshooting becomes much harder. Alpine uses musl instead of glibc. A JDK built for glibc won't run on it, and native libraries in dependencies can behave differently or fail to load.
# Builder: extract layers, derive modules with jdeps, build a custom runtime
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /build
COPY target/app.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract
# Modules jdeps cannot see (reflection/ServiceLoader). Kept in version control.
COPY jlink-extra-modules.txt .
# e.g. contents: java.naming,java.sql,jdk.crypto.ec,jdk.charsets,jdk.localedata
RUN CP=$(find dependencies snapshot-dependencies -name '*.jar' | tr '\n' ':') \
&& jdeps --ignore-missing-deps --multi-release 21 --print-module-deps \
--class-path "$CP" application/BOOT-INF/classes > jdeps-modules.txt \
&& MODULES="$(cat jdeps-modules.txt),$(cat jlink-extra-modules.txt)" \
&& echo "Linking modules: $MODULES" \
&& jlink --add-modules "$MODULES" \
--strip-debug --no-header-files --no-man-pages \
--output /opt/jre
# Runtime: glibc-based slim image (the Temurin JDK above is built for glibc)
FROM debian:bookworm-slim
ENV JAVA_HOME=/opt/jre
ENV PATH="$JAVA_HOME/bin:$PATH"
COPY --from=builder /opt/jre /opt/jre
WORKDIR /app
RUN useradd --system --uid 10001 app
# Least-changing layers first so registry caching still works
COPY --from=builder /build/dependencies/ ./
COPY --from=builder /build/spring-boot-loader/ ./
COPY --from=builder /build/snapshot-dependencies/ ./
COPY --from=builder /build/application/ ./
USER app
# Spring Boot 3.2+ launcher class; patch the JDK by bumping the builder image and rebuilding
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
A multi-stage Dockerfile that runs jdeps against the extracted layers, merges its output with an explicitly maintained module list, builds a stripped runtime with jlink, and copies it onto a glibc-based slim image.
When should you avoid a hand-written layered Dockerfile, and what are the alternatives?
Layering only pays off on repeated pulls and pushes. A node that has never seen the image still downloads every layer, so cold-start pull time on a fresh autoscaled node barely changes. Total image size also stays about the same unless you change the base image or the runtime. Caching depends on how stable your dependencies are. If your team bumps libraries or snapshot versions every few commits, the dependency layer is invalidated about as often as the application layer.
The approach is also fragile. Jarmode commands and the extracted directory layout have changed between Spring Boot releases, so a Dockerfile copied from another project can build cleanly and then fail at startup, or quietly copy an empty directory. Running from extracted directories can also break APM agents, launch scripts or security scanners that expect a single jar on disk.
| Option | Control | Maintenance effort | Image size | Patching responsibility |
|---|---|---|---|---|
| Single-layer fat jar | Low | Minimal | Baseline | You, via base image |
| Layered multi-stage Dockerfile | High | Moderate; tracks Boot changes | Similar to baseline, better cache reuse | You |
| Layered + jlink | Highest | High; module list drifts | Smaller runtime | You, including JDK rebuilds |
| Cloud Native Buildpacks via the Boot plugin | Moderate, through configuration | Low | Layered and comparable | Shared; rebuild to pick up builder updates |
For most services, buildpacks are the simpler choice. You get layering without maintaining a Dockerfile, and base image patches arrive when you rebuild.
How do you verify layer sizes and measure the cost savings?
Run docker history on the built image and read the size column from the top down. The four COPY instructions from the extracted layers should appear as separate entries. The dependencies layer should be the largest one. The application layer should hold only your compiled classes and resources. If one entry contains nearly the whole jar, extraction did not happen, or the layer order is wrong.
Next, run a cache test. Change one line in a controller, rebuild, and push.
- Build output: the dependency, loader, and snapshot steps should report as cached.
- Push output: the registry should report "layer already exists" for every layer except the application layer.
If dependencies are re-pushed, check whether a -SNAPSHOT artifact or a build timestamp is changing their contents. An image inspection tool can show per-layer file diffs if you need to find the file that changed.
Illustrative estimate (assumed numbers, not a benchmark)
Assume:
- Dependencies: 80 MB
- Application layer: 2 MB
- Pushes per day: 40
- Base image: already cached
Formula:
Daily upload avoided = pushes × (fat-jar size − application layer size)
Worked through: 40 × (82 − 2) = 3,200 MB per day. That volume of upload is avoided in CI and of new layer storage is avoided in the registry. Each environment that pulls the image saves similar egress. Replace the assumed values with your own sizes and push counts.
Re-run after Spring Boot upgrades
- Confirm the layer names your Dockerfile copies still exist in the extracted output.
- Compare layer sizes with the previous release.
- Repeat the code-only change test.
- Check that custom layer rules still match your internal libraries.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring boot layered jar docker, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.