BBackend CourseLeroy Labs
0/0
Search the course

Docker for Java with multi-stage builds, non-root users, distroless & JVM memory

Images vs containers, layer caching, multi-stage builds, layered jars, non-root and distroless runtimes, healthchecks, and container-aware JVM flags (MaxRAMPercentage, ExitOnOutOfMemoryError).

● intermediateHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

An image is an immutable, layered filesystem plus metadata. A container is a running instance of it. Each Dockerfile instruction creates a layer, and layers are cached, so put things that change rarely first.

A production Dockerfile, step by step

# ---------- build stage ----------
FROM eclipse-temurin:25-jdk-jammy AS build
WORKDIR /app
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -B -ntp dependency:go-offline        # cached unless pom.xml changes
COPY src src
RUN ./mvnw -B -ntp package -DskipTests
RUN java -Djarmode=tools -jar target/*.jar extract --layers --launcher --destination extracted

# ---------- runtime stage ----------
FROM eclipse-temurin:25-jre-jammy                # JRE only: smaller, fewer CVEs
RUN useradd --system --uid 1001 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/ ./   # only this layer changes on code edits
USER 1001
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD curl -fs http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

Why each piece

Piece Why
Multi-stage The JDK, Maven and sources stay in the build stage, so the final image is about 200 MB instead of 700 MB
dependency:go-offline first Docker caches the dependency layer, so code changes don’t re-download the internet
Layered jar Dependencies (about 80 MB) rarely change, so pushes and pulls only transfer the small app layer
Non-root user A container breakout or RCE gets fewer privileges
MaxRAMPercentage=75 The JVM sizes its heap from the container’s memory limit, leaving room for metaspace, threads and native memory
ExitOnOutOfMemoryError Crash fast and let the orchestrator restart, instead of limping along in a broken state
HEALTHCHECK Docker and orchestrators know when the app is actually ready or alive

In your projects

Report-Manager-2Dockerfile.prod

Multi-stage eclipse-temurin:25-jdk-jammy, with the layered jar extracted onto gcr.io/distroless/java25-debian13:nonroot. Distroless images have no shell and no package manager, so they have a tiny attack surface. You can’t docker exec sh into them, so debug with logs and metrics instead.

SperoTek (in dev)Dockerfile.prod · Dockerfile.dev

Temurin 25 JDK to JRE, non-root uid 1001, -XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError, SPRING_PROFILES_ACTIVE=prod, and a HEALTHCHECK on /actuator/health. A separate Dockerfile.dev is used for hot reload and debugging.

IR3D (Kontentt)Dockerfile.prod

The runtime image adds ffmpeg and yt-dlp (needed for content matching and voice-note transcoding), runs as the non-root user kontentt, and health-checks the management port :8081/actuator/health/liveness. It is built for ARM (cheaper Graviton EC2).

Hostel-Web-AppDockerfile.prod

Multi-stage with dependency:go-offline, a non-root springuser, and fixed heap flags -Xms512m -Xmx1g. Fixed -Xmx works, but it must stay in sync with the container memory by hand. MaxRAMPercentage adapts automatically.

Alternatives

Option Notes
Handwritten Dockerfile (yours) Full control
Buildpacks (./mvnw spring-boot:build-image) No Dockerfile, good defaults, automatic memory calculation
Jib Builds images without a Docker daemon, layered by default
GraalVM native image About 50 ms startup and low memory, but long builds and reflection configuration; great for serverless or scale-to-zero
Alpine base Small, but musl libc can be problematic for some native libraries
  • .dockerignore keeps target/, .git and .env out of the build context. Never bake secrets into images, because layers are readable.
  • Image scanning with Trivy, Grype or Docker Scout for CVEs.
  • Pin base images by digest for reproducibility.
  • CDS / AppCDS and Spring AOT speed up JVM startup.
  • Render free tier. Render can run a Docker web service, but free instances sleep after inactivity and cold-start slowly with the JVM. That’s one reason your course is a static site.

Check yourself

1. Why copy pom.xml and run dependency:go-offline before copying src?
2. Container limit 2GB, MaxRAMPercentage=75 → max heap ≈
3. Main trade-off of distroless images?