Docker for Spring Boot: images, multi-stage Dockerfiles, the JVM in a container and Compose
What a container is (namespaces, cgroups), layers and the build cache, a multi-stage Dockerfile with layered jars, choosing a base image, JVM memory, non-root users, PID 1 and graceful shutdown, healthchecks, Docker Compose for local development and image vulnerability scanning.
On this page
1. The problem
A 1 GB Spring Boot image takes 8 minutes to build after a one-line change. The pod gets OOMKilled with -Xmx1g and a 1 GiB limit. Every deploy produces 20–30 failed requests because containers are killed mid-flight.
2. Key idea
A container isn't a VM: the kernel gives a process its own world with namespaces (pid, net, mnt, user) and caps CPU and RAM with cgroups (memory.max, cpu.max). An image is a stack of read-only layers; when one changes, every later layer rebuilds, so rarely changing things go first.
| Base image | Compressed (amd64) | Shell | Notes |
|---|---|---|---|
eclipse-temurin:21-jdk |
225 MB | yes | build only |
eclipse-temurin:21-jre |
116 MB | yes | glibc, the safe default |
eclipse-temurin:21-jre-alpine |
74 MB | yes | musl: native libraries may hit UnsatisfiedLinkError |
gcr.io/distroless/java21-debian12 |
small | no | glibc, :nonroot tag |
2.1 What builds the image?
| Approach | Use when | Don't use when |
|---|---|---|
| Hand-written multi-stage Dockerfile | you want full control | the team won't patch base images itself |
Buildpacks (spring-boot:build-image) |
you want layers, non-root and a memory calculator built in | CI has no Docker daemon |
| Jib | CI has no Docker daemon | you need arbitrary RUN steps |
| Containers (versus VMs) | many services per host, fast startup | you need a strong security boundary (use VMs, gVisor, Kata) |
3. Dockerfile
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B -ntp dependency:go-offline
COPY src src
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B -ntp package -DskipTests \
&& java -Djarmode=tools -jar target/*.jar extract --layers --destination /extracted
FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=build /extracted/dependencies/ ./
COPY --from=build /extracted/spring-boot-loader/ ./
COPY --from=build /extracted/snapshot-dependencies/ ./
COPY --from=build /extracted/application/ ./
USER app
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
ENTRYPOINT ["java", "-jar", "orders-0.0.1-SNAPSHOT.jar"]extract --layers (Spring Boot 3.3+) splits the jar into four layers. Measured on Spring Boot 4.0.9: dependencies 21 MB, application 4 KB. Add server.shutdown=graceful and a .dockerignore excluding target/ and .git.
PID 1, healthchecks, Compose and vulnerability scans
- PID 1: a shell-form
ENTRYPOINT java -jar app.jarmakesshPID 1, which swallows SIGTERM; Java gets SIGKILLed after the grace period and in-flight requests are cut. Exec form (a JSON array) makes Java PID 1. - The JVM reads
JAVA_TOOL_OPTIONSitself, so no shell expansion of$JAVA_OPTSis needed. - OOMKilled (137) is the kernel killing the process for RSS above
memory.max, with no stack trace;OutOfMemoryErroris thrown by the JVM and shows in logs. HEALTHCHECK CMD curl ...silently fails in images withoutcurl(distroless). Kubernetes ignoresHEALTHCHECKand uses probes.- Compose for dev: PostgreSQL and Redis at production versions,
depends_onwithcondition: service_healthy. - Pin tags (and digests); scan images with Trivy in CI and block fixable critical CVEs.
4. Working with AI
Hand to AI: multi-stage Dockerfiles, .dockerignore, a dev compose.yaml, reading docker history and Trivy output.
Check yourself in AI-written code:
- Multiple stages; the runtime stage has only a JRE and the layered jar.
-
COPY pom.xmland dependency download happen beforeCOPY src. -
ENTRYPOINTis exec form;server.shutdown=gracefulis set. - It runs as a non-root user; the base image tag is pinned.
- No
-Xmxequal to the memory limit;MaxRAMPercentageinstead.
5. Exercises
Exercise 1: Review a Dockerfile
The Dockerfile below takes 6 minutes per one-line change, the image is over 600 MB, and every deploy drops a few requests. Find at least six problems.
FROM maven:3-eclipse-temurin-21
COPY . /app
WORKDIR /app
RUN mvn package
ENV JAVA_OPTS="-Xmx1g"
EXPOSE 8080
CMD java $JAVA_OPTS -jar target/orders-0.0.1-SNAPSHOT.jarSolution 1
- One stage: the runtime image carries the JDK, Maven, source code and the
.m2cache. COPY .before building: one changed line re-downloads every dependency; no.dockerignore.- A floating
maven:3-...tag: next month builds a different image. mvn packageruns the tests during the image build: slow, and Testcontainers fails without Docker. Tests belong in CI.- A single-layer fat jar: every deploy pushes 20+ MB again.
- Runs as root.
- Shell-form
CMD:shis PID 1, Java never gets SIGTERM, requests get cut: exactly the deploy errors. - Hard
-Xmx1g: with a 1 GiB limit it will beOOMKilled.
The fix is the Dockerfile in section 3.
Exercise 2: Read an OOMKilled incident
A pod has memory: 1Gi and JAVA_TOOL_OPTIONS=-Xmx1g. kubectl describe pod shows OOMKilled, exit 137; the logs have no OutOfMemoryError. The AI suggests raising -Xmx to 1500m. What do you answer?
Solution 2
- The kernel killed it because RSS (heap + metaspace + thread stacks + direct buffers + code cache) exceeded 1 GiB; the JVM never threw
OutOfMemoryErrorbecause the heap wasn't full. - Raising
-Xmxto 1500m makes it worse: the heap may now exceed the limit by itself. - Fix: drop the hard
-Xmx, set-XX:MaxRAMPercentage=75(~768 MB heap), measure off-heap memory with Native Memory Tracking; if you need a bigger heap, raise the limit, not-Xmx.
Summary
- A container is a process with namespaces and cgroups, sharing the host kernel.
- Rarely changing things first in the Dockerfile; multi-stage builds with a layered jar.
- The default base is a JRE on glibc; Alpine uses musl.
MaxRAMPercentageinstead of a hard-Xmx;OOMKilledis the kernel.- Exec-form
ENTRYPOINT, non-root user, graceful shutdown.
Further reading: Virtual memory, page cache and the JVM.
Self-compiled notes from official documentation and hands-on practice.
Practice interview questions on this topic
- How is a container different from a virtual machine?
- How does a Docker image differ from a container, and how do registries, tags and push/pull work?
- Which Docker commands do you use every day, and what for?
- What is a Dockerfile, and which instructions does a basic one contain?
- What is a Docker network? How do containers reach each other by name, and which network types exist?
- What is port mapping in Docker? How do -p, EXPOSE and -P differ?
Comments
Community rules