Video in progress
How do you make a Java service's Docker image smaller and more secure?
A minimal base (distroless, or a slim/alpine variant of the JRE), a runtime built with jlink from only the needed modules, a non-root user, and a vulnerability scanner in CI. But every cut also takes away some of the convenience for diagnostics.
📖 Answer
Comparing the options (sizes are approximate):
| Base | Size | Notes |
|---|---|---|
eclipse-temurin:21-jdk |
~450 MB | for building, excessive in prod |
eclipse-temurin:21-jre |
~200 MB | has a shell and a package manager |
| distroless java21 | ~200 MB | no shell, small attack surface |
| jlink runtime + minimal OS | ~80-120 MB | only the needed modules |
Your own runtime with jlink:
FROM eclipse-temurin:21-jdk AS jre
RUN jlink --add-modules java.base,java.logging,java.naming,java.sql,java.management,java.instrument,jdk.unsupported \
--strip-debug --no-man-pages --no-header-files --compress=zip-6 \
--output /opt/jre
FROM debian:12-slim
COPY --from=jre /opt/jre /opt/jre
COPY app.jar /app/app.jar
USER 10001
ENTRYPOINT ["/opt/jre/bin/java", "-jar", "/app/app.jar"]
You find the module list with jdeps --print-module-deps, but in an application rich in reflection, like a Spring one, it does not see everything. If a module is missing, the error appears only at runtime, sometimes on a rarely used path. That is why a full test run is a must.
Be careful with Alpine (musl libc): some native libraries (Netty's native transport, for example) expect glibc.
On the security side: a Trivy scan in CI, regular updates of the base image (an outdated base is the main source of CVEs), and pinning the image by digest. The size itself is secondary. The difference between 200 MB and 100 MB is often unnoticeable, and updating regularly matters more.
Sign up to mark studied questions and save your progress.