Video in progress

Senior 🌱 Spring

How do you package a Spring Boot application into a container: Dockerfile, layered jar, buildpacks and JVM memory settings?

The main decisions are: build a cache-friendly image with a layered jar or buildpacks, a small JRE-based base image, a non-root user, and a MaxRAMPercentage that matches the container limit. Setting -Xmx equal to the limit leads to an OOMKill.

📖 Answer

Building the image. If you copy the fat jar as one layer, 80 MB is re-uploaded on every deploy, even when only your 200 KB of code has changed. Boot splits the jar into layers:

FROM eclipse-temurin:21-jre AS build
WORKDIR /app
COPY target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted

FROM eclipse-temurin:21-jre
RUN useradd -r app
USER app
WORKDIR /app
COPY --from=build /app/extracted/dependencies/ ./
COPY --from=build /app/extracted/spring-boot-loader/ ./
COPY --from=build /app/extracted/snapshot-dependencies/ ./
COPY --from=build /app/extracted/application/ ./
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "org.springframework.boot.loader.launch.JarLauncher"]

(Up to Boot 3.3 you used -Djarmode=layertools ... extract.) The alternative is mvn spring-boot:build-image: you don't write a Dockerfile, and Paketo buildpacks also add a memory calculator for you.

Memory. A container limit of 1 GiB and -Xmx1g is the classic mistake. The JVM takes memory outside the heap too: metaspace, thread stacks (up to ~1 MB each), direct buffers, the JIT code cache, GC structures. The total goes over the limit, and the kernel kills the process with OOMKilled, leaving no stack trace in Java.

  • -XX:MaxRAMPercentage=70..75: the heap as a percentage of the limit.
  • If you have a lot of threads (Tomcat 200 + pools), lower the percentage.
  • Use -XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory to see the real breakdown.

Other things: if the CPU limit is very small (0.5 core), the JVM thinks it has 1 processor, picks SerialGC and startup slows down; set the GC explicitly if needed. Run the image as non-root, and write ENTRYPOINT in exec form so SIGTERM is received properly (a shell wrapper can swallow the signal).