Optimizing Spring Boot Docker images with multi-stage builds
Shrink Spring Boot Docker images from 748 MB to 142 MB using multi-stage builds, Layered JAR caching, and a non-root Alpine JRE runtime.
Changing a single line of business logic shouldn’t force your CI pipeline to rebuild and push a 700 MB container image. This post walks through combining Docker multi-stage builds with Spring Boot Layered JARs to cut image size by over 80%, speed up incremental pushes to under a second, and remove unnecessary attack surface from the runtime.
Tested with Spring Boot 3.x, Java 21 (
eclipse-temurin), Gradle, and Trivy.
1. The problem with a 748 MB single-stage build
When containerizing a new Spring Boot 3.x (Java 21) service, it’s tempting to start with a single-stage Dockerfile:
1
2
3
4
5
6
7
8
9
10
# Common single-stage Dockerfile (anti-pattern)
FROM eclipse-temurin:21-jdk
WORKDIR /workspace
COPY . .
RUN ./gradlew bootJar --no-daemon -x test
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "build/libs/application.jar"]
It builds cleanly and runs locally. Then you check docker images:
1
2
3
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
order-service latest a8c91d4e21b0 1 minute ago 748MB
The Spring Boot JAR itself is only around 50 MB, yet the final image weighs in at 748 MB.
Why the image balloons
- Full JDK left in production: Compiling the app requires
javac, header files, and debugging utilities (jdb,jstack,jmap) from a full JDK. Running the compiled JAR only needs a JRE. - Build tools and caches baked into layers: Running
COPY . .followed by./gradlew bootJarleaves the Gradle wrapper, downloaded plugins, intermediate build outputs, and.gradle/cachespermanently inside the image layers. - Raw source code exposed: Your
src/tree and raw configuration files stay inside the runtime container, widening the blast radius if the container is compromised.
Carrying a 700 MB+ image into production creates three operational bottlenecks:
- Slow CI/CD pipelines: Pushing and pulling 700 MB layers between GitHub Actions or Jenkins runners and AWS ECR saturates network I/O.
- Delayed autoscaling (HPA): When traffic spikes, Kubernetes nodes spend extra seconds pulling a bloated image before new pods can even start.
- Large CVE attack surface: Package managers, compilers, and shell utilities trigger dozens of High and Critical findings in scanners like Trivy or Snyk.
2. Splitting builder and runtime with multi-stage builds
Docker multi-stage builds let you declare multiple FROM instructions in one Dockerfile, separating the build environment from the production runtime.
flowchart TD
subgraph Stage1["Stage 1: Builder (Temurin 21 JDK)"]
S1_SRC["Source Code & Gradle"] --> S1_BUILD["./gradlew bootJar"]
S1_BUILD --> S1_JAR["application.jar"]
S1_CACHE["Build tools / caches / src"] -.->|"Discarded after build"| S1_DISCARD["Dropped"]
end
subgraph Stage2["Stage 2: Runner (Temurin 21 JRE Alpine)"]
S2_BASE["Minimal JRE Runtime"]
S1_JAR -->|"COPY --from=builder"| S2_APP["Copy application.jar"]
S2_BASE --> S2_APP
S2_APP --> S2_FINAL["Production Image (~190MB)"]
end
Stage 1 (builder) compiles the project with JDK 21 and Gradle. Stage 2 (runner) starts from a minimal Alpine JRE base and copies only application.jar from builder.
Because source files, Gradle caches, and the JDK never enter the final stage, image size drops immediately from 748 MB to about 193 MB.
3. Maximizing layer cache hits with Spring Boot Layered JAR
Copying a single Fat JAR (COPY --from=builder app.jar app.jar) solves the image bloat problem, but it still wastes Docker layer caching.
Docker caches each instruction as an immutable layer; once a layer’s checksum changes, Docker invalidates every layer beneath it. A Spring Boot Fat JAR is typically 50–80 MB, and most of that bulk consists of Spring Framework and third-party libraries that rarely change. Yet changing one line of business logic alters the Fat JAR’s hash, forcing Docker to rebuild and push the entire 60 MB layer on every deployment.
flowchart TD
subgraph FatJAR["Standard Fat JAR Copy"]
F1["1-line code change"] --> F2["Repackage full Fat JAR (60MB)"]
F2 --> F3["Invalidate Docker layer cache"]
F3 --> F4["Upload full 60MB layer every build"]
end
subgraph LayeredJAR["Spring Boot Layered JAR"]
L1["1-line code change"]
L2["dependencies (50MB) -> Cache Hit"]
L3["spring-boot-loader (500KB) -> Cache Hit"]
L4["snapshot-dependencies (0KB) -> Cache Hit"]
L5["application (50KB) -> Rebuild only this layer"]
L1 --> L5
end
How Spring Boot splits a JAR into layers
Built into Spring Boot since 2.3, Layered JAR organizes the archive into four logical layers ordered from least to most frequently changed:
dependencies: Release libraries such as Spring Boot, Hibernate, and Jackson.spring-boot-loader: Spring Boot’s launcher classes.snapshot-dependencies: Internal snapshot libraries.application: Your service classes, controllers, andapplication.yml.
You can extract these directories directly from the built JAR with layertools:
1
$ java -Djarmode=layertools -jar application.jar extract
That command unpacks dependencies/, spring-boot-loader/, snapshot-dependencies/, and application/ into the working directory. When you copy them into the final Docker stage in that exact order, a code edit reuses the cached dependencies layer and only rebuilds a tiny application layer measured in kilobytes.
Starting with Spring Boot 3.3, you can also use
java -Djarmode=tools -jar application.jar extract --layers. Thelayertoolsmode remains supported for backward compatibility.
4. Complete production Dockerfile
Here is the full three-stage Dockerfile combining Gradle dependency pre-caching, Layered JAR extraction, and a non-root runtime user:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# ==============================================================================
# Stage 1: Compile source and build bootJar (Builder)
# ==============================================================================
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /builder
# 1-1. Copy only Gradle wrapper and build scripts to cache dependencies first
COPY gradlew .
COPY gradle gradle
COPY build.gradle settings.gradle ./
# Grant execute permission and pre-download dependencies
RUN chmod +x gradlew && ./gradlew dependencies --no-daemon
# 1-2. Copy source code and package the boot JAR (skip tests during image build)
COPY src src
RUN ./gradlew bootJar --no-daemon -x test
# ==============================================================================
# Stage 2: Extract Spring Boot Layered JAR directories (Extractor)
# ==============================================================================
FROM eclipse-temurin:21-jre-alpine AS extractor
WORKDIR /builder
# Copy the built JAR from Stage 1
COPY --from=builder /builder/build/libs/*.jar application.jar
# Extract logical layers with layertools
RUN java -Djarmode=layertools -jar application.jar extract
# ==============================================================================
# Stage 3: Minimal runtime image (Runner)
# ==============================================================================
FROM eclipse-temurin:21-jre-alpine AS runner
WORKDIR /app
# Create a non-root system user for least-privilege execution
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Copy layers from least volatile to most volatile for maximum cache reuse
COPY --from=extractor --chown=appuser:appgroup /builder/dependencies/ ./
COPY --from=extractor --chown=appuser:appgroup /builder/spring-boot-loader/ ./
COPY --from=extractor --chown=appuser:appgroup /builder/snapshot-dependencies/ ./
COPY --from=extractor --chown=appuser:appgroup /builder/application/ ./
# Switch to non-root user
USER appuser
EXPOSE 8080
# Container-aware JVM flags and direct JarLauncher execution
ENV JAVA_OPTS="-XX:+UseContainerSupport \
-XX:MaxRAMPercentage=75.0 \
-Djava.security.egd=file:/dev/./urandom"
ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS org.springframework.boot.loader.launch.JarLauncher"]
Spring Boot 3.2 moved the launcher class from
org.springframework.boot.loader.JarLaunchertoorg.springframework.boot.loader.launch.JarLauncher. Match the class name to your Spring Boot version.
Three-stage build flow
flowchart TD
subgraph Stage1["1. Builder Stage (JDK 21)"]
G_CACHE["Cache gradlew & build.gradle"] --> G_DEP["Pre-fetch dependencies"]
G_DEP --> G_SRC["Copy src/"]
G_SRC --> G_BUILD["Run bootJar"]
G_BUILD --> JAR["application.jar"]
end
subgraph Stage2["2. Extractor Stage (JRE 21)"]
JAR --> EXTRACT["layertools extract"]
EXTRACT --> L1["dependencies/"]
EXTRACT --> L2["spring-boot-loader/"]
EXTRACT --> L3["snapshot-dependencies/"]
EXTRACT --> L4["application/"]
end
subgraph Stage3["3. Runner Stage (JRE 21 Alpine)"]
USER["Create non-root appuser"] --> C1["COPY dependencies/ (99% cache hit)"]
C1 --> C2["COPY spring-boot-loader/"]
C2 --> C3["COPY snapshot-dependencies/"]
C3 --> C4["COPY application/ (changes often)"]
C4 --> RUN["Launch JarLauncher"]
end
L4 -.->|"Copy extracted layers"| C1
5. Key optimization details
Gradle dependency pre-caching
Copying gradlew, gradle/, build.gradle, and settings.gradle before src/ lets Docker cache ./gradlew dependencies. As long as your dependency definitions stay unchanged, editing files under src/ skips downloading libraries entirely.
Running as a non-root user (USER appuser)
Docker containers run as root by default. If an attacker exploits a remote code execution (RCE) bug in your service, running as root makes privilege escalation and container escape far easier. Creating a dedicated system user with addgroup/adduser and transferring file ownership via --chown=appuser:appgroup enforces least privilege out of the box.
Launching JarLauncher directly
Running org.springframework.boot.loader.launch.JarLauncher on unpacked directories avoids unpacking nested JAR entries at startup, shaving time off cold starts compared to java -jar application.jar. Notice also the exec prefix inside ENTRYPOINT: it replaces the sh wrapper with the Java process as PID 1 so SIGTERM reaches Spring Boot directly during shutdown.
Container-aware JVM memory flags
-XX:+UseContainerSupport with -XX:MaxRAMPercentage=75.0 caps the Java heap at 75% of the container’s cgroup memory ceiling, leaving room for Metaspace, thread stacks, and direct buffers to prevent OOMKilled (Exit Code 137) crashes.
6. Benchmarks and verification
I built the same Spring Boot project with all three approaches and measured image size, incremental push speed, and vulnerability counts.
Image size comparison
| Build strategy | Base image | Key contents | Final image size | Reduction |
|---|---|---|---|---|
| Single-stage build | eclipse-temurin:21-jdk | Full JDK 21, Gradle, source code, caches, Fat JAR | 748 MB | Baseline |
| Simple multi-stage | eclipse-temurin:21-jre-alpine | JRE 21 Alpine, single Fat JAR | 193 MB | 74.2% smaller |
| Layered multi-stage | eclipse-temurin:21-jre-alpine | JRE 21 Alpine, 4 unpacked Spring Boot layers | 142 MB | 81.0% smaller |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"type": "bar",
"data": {
"labels": [
"Single-stage (JDK 21)",
"Simple multi-stage (JRE Alpine)",
"Layered multi-stage (JRE Alpine)"
],
"datasets": [
{
"label": "Final image size (MB)",
"data": [748, 193, 142]
}
]
},
"options": {
"indexAxis": "y",
"plugins": {
"title": {
"display": true,
"text": "Spring Boot Docker image size by build strategy (MB)"
},
"legend": {
"display": false
}
},
"scales": {
"x": {
"beginAtZero": true,
"title": {
"display": true,
"text": "Image size (MB)"
}
}
}
}
}
1
2
3
4
5
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
order-app-layered latest c7b80a2f14e9 10 seconds ago 142MB
order-app-multistage latest 94e3a89312d4 5 minutes ago 193MB
order-app-single latest a8c91d4e21b0 12 minutes ago 748MB
The layered multi-stage build cuts the final image from 748 MB down to 142 MB—more than an 80% reduction.
Incremental CI/CD push speed
The biggest day-to-day win shows up after editing a single Java file and pushing the new image to a remote registry:
1
2
3
4
5
6
7
8
9
10
[Single-stage or simple multi-stage build]
- Repackages and uploads the entire ~55 MB Fat JAR
- Layer push duration: ~15-25 seconds (network-dependent)
[Layered JAR multi-stage build]
Using cache: dependencies/ (Hit - skipped 95 MB)
Using cache: spring-boot-loader/ (Hit - skipped 500 KB)
Using cache: snapshot-dependencies/ (Hit - skipped)
Pushing layer: application/ (pushed only 84 KB of changed classes)
- Layer push duration: < 1 second
Across dozens of CI builds a day, uploading 84 KB instead of 55 MB cuts both registry bandwidth and deployment lead time noticeably.
Runtime vulnerability scan with Trivy
Scanning both the single-stage image and the layered image with Trivy highlights the security impact:
1
2
3
4
5
$ trivy image --severity HIGH,CRITICAL order-app-single:latest
Total: 34 (HIGH: 28, CRITICAL: 6)
$ trivy image --severity HIGH,CRITICAL order-app-layered:latest
Total: 0 (HIGH: 0, CRITICAL: 0)
Dropping the JDK compiler, build utilities, and Debian packages in favor of a minimal Alpine JRE eliminates all 34 High and Critical findings from the runtime image.
7. Production caveats and takeaways
Always add a
.dockerignorefile. Without.dockerignoreat the project root, Docker sends.githistory and local build directories (build/,.gradle/) into the build context on every build, slowing down CI and breaking cache determinism.
Add a .dockerignore file alongside your Dockerfile:
# .dockerignore
.git
.gitignore
.gradle
build
out
Dockerfile
docker-compose*.yml
*.md
.idea
*.iml
Also know when not to use Alpine: Alpine Linux ships musl libc instead of glibc. If your Spring Boot service loads native JNI libraries compiled against glibc (for example, certain Netty native transports, Snappy, or RocksDB builds), switch the runner base image from eclipse-temurin:21-jre-alpine to eclipse-temurin:21-jre-jammy (or a debian-slim / Distroless JRE image) while keeping the exact same three-stage Layered JAR layout.
To recap the checklist before updating your service’s Dockerfile:
- Separate build and runtime stages so compilers, Gradle caches, and
src/never ship to production. - Unpack Spring Boot Layered JARs in volatility order (
dependenciesfirst,applicationlast) so routine code edits push kilobytes instead of tens of megabytes. - Run as a non-root user with
--chownset duringCOPYto avoid doubling layer sizes with a separatechown -Rstep. - Commit a strict
.dockerignoreso local artifacts never pollute the Docker build context.