Video in progress

Strong Middle ⚙️ JVM and memory

How does building a custom runtime with jlink shrink a container image, and what should you watch out for?

jlink builds a runtime from only the JDK modules the application needs: 50-80 MB instead of a 300+ MB JDK. jdeps gives you the list of needed modules, but modules used through reflection and service loading often get missed, and diagnostic tools disappear too.

📖 Answer

Finding the needed modules:

jdeps --ignore-missing-deps --multi-release 21 --print-module-deps \
      --class-path 'BOOT-INF/lib/*' app.jar
# java.base,java.desktop,java.instrument,java.management,java.naming,java.sql,...

Building the runtime:

FROM eclipse-temurin:21-jdk AS build
RUN jlink --add-modules java.base,java.logging,java.management,java.naming,java.sql,jdk.crypto.ec,jdk.jfr,jdk.jcmd \
          --strip-debug --no-man-pages --no-header-files --compress=zip-6 \
          --output /opt/jre

FROM debian:bookworm-slim
COPY --from=build /opt/jre /opt/jre
COPY app.jar /app/app.jar
ENTRYPOINT ["/opt/jre/bin/java", "-jar", "/app/app.jar"]

What to watch out for:

  • Hidden dependencies. jdeps does static analysis. jdk.crypto.ec (elliptic curves for TLS), jdk.charsets, jdk.localedata and jdk.zipfs are often used through reflection or ServiceLoader. If they are missing, an HTTPS connection or locale formatting fails at runtime. Run your integration tests on exactly this image.
  • Diagnostics. If you don't add jdk.jcmd and jdk.jfr, you won't have jcmd and JFR on prod. Don't give them up to save a few MB.
  • Updating. When a JDK patch comes out, the runtime has to be rebuilt. Automate it in CI.
  • --compress=zip-6 is JDK 21 syntax; in older versions it is --compress=2.

The benefit isn't only size: fewer modules means fewer CVEs in security scanners. But if you already have a -jre image and the difference is 10 MB, the complexity of jlink may not be justified.