SteelReed

Search

Search posts, questions…

6. DevOps & Operations

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.

18 Nov 20268 min readMid

–

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

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.jar makes sh PID 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_OPTIONS itself, so no shell expansion of $JAVA_OPTS is needed.
  • OOMKilled (137) is the kernel killing the process for RSS above memory.max, with no stack trace; OutOfMemoryError is thrown by the JVM and shows in logs.
  • HEALTHCHECK CMD curl ... silently fails in images without curl (distroless). Kubernetes ignores HEALTHCHECK and uses probes.
  • Compose for dev: PostgreSQL and Redis at production versions, depends_on with condition: 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.xml and dependency download happen before COPY src.
  • ENTRYPOINT is exec form; server.shutdown=graceful is set.
  • It runs as a non-root user; the base image tag is pinned.
  • No -Xmx equal to the memory limit; MaxRAMPercentage instead.

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.

DOCKERFILE
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.jar
Solution 1
  1. One stage: the runtime image carries the JDK, Maven, source code and the .m2 cache.
  2. COPY . before building: one changed line re-downloads every dependency; no .dockerignore.
  3. A floating maven:3-... tag: next month builds a different image.
  4. mvn package runs the tests during the image build: slow, and Testcontainers fails without Docker. Tests belong in CI.
  5. A single-layer fat jar: every deploy pushes 20+ MB again.
  6. Runs as root.
  7. Shell-form CMD: sh is PID 1, Java never gets SIGTERM, requests get cut: exactly the deploy errors.
  8. Hard -Xmx1g: with a 1 GiB limit it will be OOMKilled.

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 OutOfMemoryError because the heap wasn't full.
  • Raising -Xmx to 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.
  • MaxRAMPercentage instead of a hard -Xmx; OOMKilled is 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

All DevOps & Cloud questions →

Loading comments…
Next on the roadmapCI/CD for a Spring Boot backend: a GitHub Actions pipeline from commit to production