Why does a naive Spring Boot Dockerfile waste bandwidth and storage?
The typical first Dockerfile for a Spring Boot service starts from a JDK base image, copies the fat jar produced by mvn package or gradle bootJar, and sets java -jar as the entrypoint. It works, but it caches badly.
Docker identifies each layer by a digest of its contents. The fat jar is one file containing your classes and every dependency jar, so COPY app.jar produces one opaque layer. Change one line in a controller and the jar's bytes change, which changes the digest and invalidates the whole layer. The base image layers stay cached. The jar layer, which is most of what your build adds, is rebuilt, pushed to the registry, stored as a new blob, and pulled by every node that runs the new version. The dependencies inside it are almost always identical to the previous version.
Illustrative estimate. Assume 60 MB of dependencies, 200 KB of application classes, and 20 commits per day that each produce a pushed image. Compression and registry deduplication are ignored.
| Per day (20 pushes) | Naive single-jar layer | Layered (deps separate from classes) |
|---|---|---|
| Changed layer per commit | ~60.2 MB | ~0.2 MB |
| Bytes pushed | ~1.2 GB | ~4 MB, plus one 60 MB push when dependencies change |
| New registry storage | ~1.2 GB | ~4 MB |
The fix is to split the jar into several layers and order them by how often they change. Third-party dependencies, which change rarely, go at the bottom. Application classes, which change on every commit, go at the top. A typical commit then rebuilds and ships only the small top layer, and the large dependency layer stays cached in the build, the registry, and each node.
# Naive Dockerfile: the whole fat jar becomes ONE layer.
# Any change to application code changes the jar's bytes,
# so this layer gets a new digest and is rebuilt, pushed,
# stored, and pulled again in full (deps included).
# Base image layers: cached and shared across builds
FROM eclipse-temurin:21-jdk
WORKDIR /app
# Fat jar from `mvn package` (target/) or `gradle bootJar` (build/libs/).
# ~60 MB of dependency jars + ~200 KB of your classes, packed into one file.
# A one-line controller edit invalidates this entire ~60.2 MB layer.
COPY target/demo-service-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
A typical first Spring Boot Dockerfile that copies the fat jar onto a JDK image as a single layer, which is rebuilt and re-shipped in full on every code change.
What is a Spring Boot layered jar and how does it work?
A layered jar is a normal executable Spring Boot jar with one addition: a layers index, stored as BOOT-INF/layers.idx, that sorts every entry in the archive into a named group. The JVM ignores this index when it runs the jar. It exists so that a build tool can unpack the jar into separate directories that map cleanly to image layers. By default there are four groups, ordered from least to most frequently changed:
dependencies: third-party release artifacts, usually the bulk of the jar's size.spring-boot-loader: the launcher classes that bootstrap the application.snapshot-dependencies:-SNAPSHOTartifacts, which can change between builds without a version bump.application: your compiled classes and resources.
The order is what makes caching work. Docker invalidates a layer and every layer above it. Putting volatile content last keeps the expensive layers stable.
A multi-stage build uses the index in three steps. A builder stage with a full JDK and build tool compiles the project and produces the jar. An extraction step runs the jar in a special tooling mode (-Djarmode=...) to unpack it into one directory per layer. A runtime stage, starting from a slim JRE base, then copies each directory with its own COPY --from instruction in the index order.
Only what you explicitly copy with COPY --from reaches the final image. The JDK, the build tool, the source tree, the local dependency cache and the original fat jar all stay behind in discarded stages.
The extraction command and its options have changed across Spring Boot releases, including the jar mode name, flags and output layout. Check your version's reference documentation for the supported form.
+--------------------------------------------------------------+
| BUILDER STAGE (full JDK + build tool) |
| source tree + dependency cache --> compile --> app.jar |
| app.jar contains BOOT-INF/layers.idx (layers index) |
+------------------------------+-------------------------------+
|
v
+--------------------------------------------------------------+
| EXTRACTION STEP java -Djarmode=... (form varies by version)|
| reads layers.idx and writes one directory per layer: |
| [dependencies] [spring-boot-loader] |
| [snapshot-dependencies] [application] |
+------------------------------+-------------------------------+
|
COPY --from, one instruction per layer, in index order
|
v
+--------------------------------------------------------------+
| RUNTIME STAGE (slim JRE base) = final image |
| layer 4: application <-- changes most often |
| layer 3: snapshot-dependencies |
| layer 2: spring-boot-loader |
| layer 1: dependencies <-- changes least often |
| base: JRE |
+--------------------------------------------------------------+
A changed layer invalidates only itself and the layers above.
Left behind in discarded stages (never copied): JDK, build
tool, source tree, dependency cache, original fat jar
A multi-stage build compiles a layered jar, extracts it into one directory per layer using the layers index, and copies only those directories into a slim runtime image, ordered from least to most frequently changed.
How do you implement a multi-stage Dockerfile with layered jar extraction?
Builder stage: cache dependency resolution
Start from a JDK image and copy only the build descriptor and wrapper files: pom.xml, mvnw, and .mvn/ for Maven, or build.gradle(.kts), settings.gradle(.kts), gradlew, and gradle/ for Gradle. Then run a dependency-resolution step. Copy src/ only after that.
Docker caches each instruction based on its inputs. A source edit therefore leaves the resolution layer untouched. Any change to the descriptor changes the input checksum of that COPY, which invalidates it and every later instruction. A version bump or a new plugin causes a full re-download.
Docker caches each instruction based on its inputs. Add a BuildKit cache mount on the resolution and build steps, for example RUN --mount=type=cache,target=/root/.m2. Point the target at the Gradle home instead if you use Gradle. With the mount, artifacts persist across builds even when the layer is invalidated, and they are never written into the image.
Extraction stage
Run the packaged jar in Spring Boot's jar mode to split it into layer directories. These are typically dependencies, spring-boot-loader, snapshot-dependencies and application.
Runtime stage
Use a JRE-only base. Add one COPY --from=<extract-stage> per layer, ordered from least to most volatile, so that a code-only change rebuilds and pushes just the final layer.
Finish with an exec-form ENTRYPOINT. That form lets the JVM run as PID 1 and receive SIGTERM directly. Point it at either the launcher class or the extracted jar, depending on the layout your version produces.
The launcher's fully qualified class name differs between Spring Boot major versions. A stale name left in the ENTRYPOINT after an upgrade is a common cause of ClassNotFoundException at startup.
# syntax=docker/dockerfile:1
# --- Builder: resolve dependencies before copying source ---
FROM eclipse-temurin:21-jdk AS build
WORKDIR /workspace
# Descriptor and wrapper only. This layer is invalidated only when these files change.
COPY mvnw pom.xml ./
COPY .mvn/ .mvn/
# The cache mount keeps ~/.m2 between builds and never writes it into the image.
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offline
# Source edits invalidate the build from here down. Dependency resolution stays cached.
COPY src/ src/
RUN --mount=type=cache,target=/root/.m2 \
./mvnw -B package -DskipTests && cp target/*.jar app.jar
# --- Extraction: split the fat jar into layer directories ---
FROM eclipse-temurin:21-jdk AS extract
WORKDIR /workspace
COPY --from=build /workspace/app.jar app.jar
# Spring Boot 3.3+ uses the 'tools' jar mode.
# Older versions use: java -Djarmode=layertools -jar app.jar extract
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted
# --- Runtime: JRE only, layers ordered from least to most volatile ---
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=extract /workspace/extracted/dependencies/ ./
COPY --from=extract /workspace/extracted/spring-boot-loader/ ./
COPY --from=extract /workspace/extracted/snapshot-dependencies/ ./
COPY --from=extract /workspace/extracted/application/ ./
# Exec form makes the JVM PID 1, so it receives SIGTERM directly.
# The launcher class is org.springframework.boot.loader.launch.JarLauncher on Boot 3.2+.
# On Boot 2.x it is org.springframework.boot.loader.JarLauncher.
# A stale name here causes ClassNotFoundException at startup.
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
A three-stage Maven Dockerfile that caches dependency resolution with a BuildKit cache mount, extracts the Spring Boot layers in jar mode, and copies the layers in order of volatility before starting the version-specific JarLauncher in exec form.
How can you customize layers for internal libraries and frequently bumped modules?
The four default layers treat every released artifact the same, so an internal library you publish weekly sits in the dependencies layer next to Spring, Jackson and Netty. Each time that library's version is bumped, the whole dependency layer is rebuilt and pushed, even though the third-party jars inside it are unchanged. Giving internal code its own layer limits the change to a small slice of the image.
Both build plugins let you define custom layers. Maven reads an XML layers file referenced from the Spring Boot plugin's layers configuration. Gradle uses a layered block inside the bootJar task. In either case you declare three things:
- Dependency rules. Rules match dependencies by
groupId:artifactId:versionpatterns, such as your company's group ID with wildcards. Rules are evaluated in order and the first match wins. Put the internal-library rule before the catch-all rule, or the catch-all will claim those jars first. - Application rules. These assign your own classes and resources. You might split a frequently edited module from more stable code here.
- Layer order. List layers from least to most frequently changed. Docker invalidates every layer after the first changed one, so a volatile layer placed early defeats the purpose.
To verify the result, run the jar with the layer tools jar mode and its list command. Older releases use layertools, and newer ones use tools with a list-layers command. Confirm that your custom layer appears in the expected position and that your Dockerfile copies the layers in that same order.
This change helps teams with stable third-party dependencies and fast-moving internal modules the most. That pattern is common in organizations with shared platform libraries. If your internal code rarely changes, the extra layer adds configuration without any real gain.
// build.gradle (Groovy DSL): custom layers for the Spring Boot bootJar task
bootJar {
layered {
application {
// Loader classes rarely change; keep them in their own layer
intoLayer("spring-boot-loader") {
include "org/springframework/boot/loader/**"
}
// Everything else from this project (classes, resources)
intoLayer("application")
}
dependencies {
// First match wins, so specific rules go before the catch-all
intoLayer("application") {
includeProjectDependencies() // sibling modules in a multi-project build
}
intoLayer("snapshot-dependencies") {
include "*:*:*SNAPSHOT"
}
// Internal libraries bumped often (placeholder group ID)
intoLayer("company-dependencies") {
include "com.example.platform:*"
}
// Catch-all: stable third-party jars (Spring, Jackson, Netty...)
intoLayer("dependencies")
}
// Least to most frequently changed
layerOrder = ["dependencies", "spring-boot-loader",
"snapshot-dependencies", "company-dependencies", "application"]
}
}
// Verify after ./gradlew bootJar
// Newer Spring Boot releases:
// java -Djarmode=tools -jar build/libs/app.jar list-layers
// Older releases:
// java -Djarmode=layertools -jar build/libs/app.jar list
// Expected output order:
// dependencies
// spring-boot-loader
// snapshot-dependencies
// company-dependencies
// application
This Gradle bootJar configuration puts internal com.example.platform libraries in their own company-dependencies layer, ahead of the application layer and after the stable third-party dependencies layer, and the comments at the end show how to list the layers the jar reports.
Should you use distroless runtime images, and how do you harden the final image?
Distroless runtime images keep only what the JVM needs: a C library, CA certificates, timezone data, and the Java runtime. They drop the shell, the package manager, and most userland utilities. The image gets smaller, and vulnerability scanners report fewer findings because packages you never run are no longer present. Use the nonroot variant so the process starts as an unprivileged UID without a USER instruction you have to maintain.
Without a shell, ENTRYPOINT must use JSON exec form. Shell form wraps the command in /bin/sh -c, which does not exist in the image, so the container fails at startup. Exec form also runs the JVM as PID 1, so it receives SIGTERM directly and Spring Boot can shut down gracefully.
For runtime hardening:
- Memory: use
-XX:MaxRAMPercentageinstead of a hard-coded-Xmx. The heap then scales with the container's memory limit and leaves room for metaspace, thread stacks, and direct buffers. - Configuration: pass settings through environment variables. The JVM reads
JAVA_TOOL_OPTIONS, and Spring's relaxed binding maps variables likeSERVER_PORTto properties. Nothing needs to be baked into the image.
A smaller image is not automatically more secure. The JVM and your dependency tree remain the main attack surface. Base images also need regular rebuilds to pick up patches.
Plan for debugging before you need it:
- Use the debug image variants, which include a busybox shell, when you need shell access.
- Attach ephemeral containers with
kubectl debugto a running pod. - Expose diagnostics over the network, such as Actuator endpoints or remote JMX, on a restricted port.
- Use HTTP-based orchestrator probes for health checks instead of a
HEALTHCHECKthat callscurl, sincecurlis not in the image.
What are the alternatives to a multi-stage Dockerfile? Jib compared
Jib takes a different approach. It is a Maven or Gradle plugin that assembles an OCI image straight from your build output and pushes it to a registry without a Docker daemon or a Dockerfile. It does not run the fat jar. It puts dependencies, snapshot dependencies, resources and classes into separate layers and launches the application with an explicit classpath. That layering comes from Jib, not from Spring Boot's layers.idx, so the custom layer rules from earlier sections do not apply. You tune layers through Jib's own configuration.
You set the runtime image with from.image, and you pass heap and GC settings through container.jvmFlags. By default, Jib fixes file timestamps and the image creation time. If your inputs are unchanged, the image digest stays the same, so caches and digest-based promotion work without extra effort.
The trade-off is control. Jib has no RUN step, so you cannot install OS packages or add custom CA certificates at build time. If you need either, you have to build and maintain your own base image. That separate image is the hidden maintenance cost.
jlink custom runtimes and native compilation can shrink images further. They bring their own toolchains and compatibility issues, and this article does not cover them.
| Aspect | Multi-stage Dockerfile | Jib |
|---|---|---|
| Control | Full: any RUN, packages, certs |
Limited to plugin options and base image |
| Maintenance | You own the Dockerfile | You own plugin config, plus a base image if customized |
| Daemon required | Yes, for typical builds | No, when pushing directly to a registry |
| Debuggability | Build steps visible and reproducible locally | Fewer moving parts, but the image structure is less obvious |
When should you avoid layered images, and how do you verify they save time and cost?
Layering pays off only when the lower layers stay stable between builds. If they change on most commits, every push re-uploads the large layers anyway, and you have added Dockerfile complexity for no gain.
| Situation | Why layering underdelivers | Mitigation |
|---|---|---|
| Frequent dependency bumps | Dependencies layer invalidated on each update | Batch updates instead of merging each one separately |
| SNAPSHOT dependencies | Snapshot layer changes on every build | Release internal libraries or give them a dedicated layer |
| Unpinned or daily-rebuilt base image | Every layer above it rebuilds | Pin the base by digest and update it on purpose |
| Ephemeral CI runners | Local BuildKit cache is lost between jobs | Configure a registry or remote cache |
Tooling that expects java -jar |
Scripts and APM agent setup break on the exploded layout | Update the entrypoint and test agents explicitly |
The extraction step and launcher entrypoint depend on the Spring Boot loader, which can change between releases. A Boot upgrade can produce an image that builds but fails to start. CI should run the built image and check a health endpoint, not just build it.
Illustrative estimate (assumed numbers, not a benchmark): time saved per day = (full image size − app layer size) ÷ upload throughput × pushes per day. With a 300 MB image, a 10 MB app layer, 20 MB/s throughput and 40 pushes per day: 290 ÷ 20 × 40 = 580 s, or about 10 minutes of waiting removed per day.
Verification routine
- Run
docker historyon the image. Confirm that dependency layers are large and the application layer is small. - Make a code-only change, rebuild and push. Only the application layer should upload. The registry should report the other layers as already existing.
- Run the image locally with
--memoryset to the limit you use in production. Check startup time, confirm the JVM sizes its heap to fit inside the limit, and make sure the container is not OOM-killed under load.
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 docker layered jar, 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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.