Skip to content
javahacks.dev
DevOps

How to Use jlink to Build a Slim Java Runtime in Docker

Build a custom Java runtime with jlink that contains only the modules your app needs, and package it into a small Docker image with a multi-stage build.

7 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the Docker, GitHub Actions and Kubernetes logos.

A full JRE contains Java modules you never use: desktop libraries, scripting engines, management tools. The module system, introduced in Java 9, lets you build a runtime with only what your application needs. jlink does it, and in a container the result can shrink the runtime layer to a fraction of the standard JRE image. This post builds one for a Spring Boot application and puts it in a Docker image. The wider size discussion is in building a small Docker image.

Which modules does the application need?

Extract the Spring Boot jar so its dependencies are plain jars, then ask jdeps:

Shell
java -Djarmode=tools -jar target/shop.jar extract --destination extracted
jdeps --ignore-missing-deps --recursive --multi-release 25 \
      --print-module-deps --class-path 'extracted/lib/*' extracted/shop.jar

The output is a comma-separated list such as java.base,java.logging,java.naming,java.sql,java.xml,jdk.unsupported. --ignore-missing-deps keeps jdeps from failing on optional dependencies, and --multi-release 25 reads the versioned class files for your runtime. The list is a starting point, not a guarantee.

What jdeps cannot see

jdeps analyses bytecode references. It misses modules used through reflection, ServiceLoader providers and dynamic loading, which frameworks rely on. Typical additions for a web application:

ModuleNeeded for
java.sqlJDBC
jdk.crypto.ecElliptic-curve TLS cipher suites
jdk.unsupportedsun.misc.Unsafe, used by Netty, Hibernate, Kryo
java.managementJMX, Micrometer metrics
java.namingJNDI, some drivers
jdk.zipfsZip file systems
jdk.jcmdjcmd for diagnostics

A missing jdk.crypto.ec is a classic: the application works until it makes an HTTPS call to a server that requires an EC cipher, and fails with a handshake error that looks like a certificate problem (PKIX errors are a different one). Include modules deliberately and test TLS.

Build the runtime

Shell
jlink \
  --add-modules java.base,java.logging,java.naming,java.sql,java.xml,java.management,jdk.unsupported,jdk.crypto.ec \
  --strip-debug --no-man-pages --no-header-files --compress=zip-6 \
  --output /javaruntime

--strip-debug removes debug information, --no-man-pages and --no-header-files drop files a runtime does not need, and --compress=zip-6 compresses the modules (the option syntax changed in Java 21, where zip-0 to zip-9 replaced the numeric levels). The output directory is a complete Java runtime with its own bin/java.

In a multi-stage Dockerfile

Dockerfile
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY . .
RUN ./mvnw -q -DskipTests package \
 && java -Djarmode=tools -jar target/shop.jar extract --destination /extracted

RUN jlink \
    --add-modules java.base,java.logging,java.naming,java.sql,java.xml,java.management,jdk.unsupported,jdk.crypto.ec \
    --strip-debug --no-man-pages --no-header-files --compress=zip-6 \
    --output /javaruntime

FROM debian:bookworm-slim
ENV JAVA_HOME=/opt/java
ENV PATH="${JAVA_HOME}/bin:${PATH}"
RUN useradd --system --uid 10001 app
COPY --from=build /javaruntime ${JAVA_HOME}
WORKDIR /app
COPY --from=build /extracted/ ./
USER app
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=65", "-jar", "shop.jar"]

The runtime is built from the same JDK that built the application, so the versions match. The final image is a slim Debian with the custom runtime. Compare the size with the ordinary JRE image using docker images; the saving depends on how many modules you needed, and Spring Boot applications use many. Measure before committing to the extra build complexity.

Trade-offs

  • Debuggability. No jcmd, jstack or jmap unless you add jdk.jcmd and related modules. Decide how you will diagnose production; see jcmd, jstack and jmap.
  • Security updates. You build the runtime, so you must rebuild when the JDK gets a security update. Base images from a vendor update automatically in their own cadence.
  • Compatibility. A missing module fails at runtime, sometimes only on one code path. Run your full test suite and a smoke test against the final image.
  • Complexity. An extra step in the build, and a module list to maintain when dependencies change.
  • Class data sharing. jlink can include a CDS archive for faster startup (--generate-cds-archive), which helps start-up time.

When it is worth it

It is worth it when image size matters: many small services pulled onto many nodes, constrained edge devices or strict size budgets. For a few services on a fast network, a standard JRE image plus layered jars gives most of the benefit with no maintenance. Native images take the idea further at a higher cost (why Quarkus starts fast).

Automate the module list

Maintaining the --add-modules list by hand fails the first time someone adds a dependency. Compute the baseline in the build and add the known extras on top, so the only manual part is the list of modules that analysis cannot see:

Shell
#!/bin/sh
set -eu

MODULES="$(jdeps --ignore-missing-deps --recursive --multi-release 25 \
    --print-module-deps -cp 'extracted/dependencies/lib/*' extracted/application/shop.jar)"

EXTRAS="jdk.crypto.ec,jdk.unsupported,java.management,jdk.zipfs"

jlink --add-modules "${MODULES},${EXTRAS}" \
      --strip-debug --no-man-pages --no-header-files --compress=zip-6 \
      --output /opt/runtime

/opt/runtime/bin/java --list-modules

--print-module-deps prints the list in the exact comma-separated form jlink expects. The final command lists what ended up in the runtime, which you can paste into the pull request when the list changes. The extras live in one file with a comment per entry saying which library needs it, so the next engineer knows why jdk.zipfs is there and when it can go.

Prove the image works, including TLS

The failure mode of a slim runtime is a module missing on a code path your tests did not take. A smoke test that touches the usual suspects catches most of them. This small class makes a TLS connection, reads a resource from the classpath, opens a zip file system and registers a JMX bean:

java
public class RuntimeSmokeTest {

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<Void> response = client.send(
            HttpRequest.newBuilder(URI.create("https://example.com")).build(),
            HttpResponse.BodyHandlers.discarding());
        System.out.println("tls ok, status " + response.statusCode());

        Path zip = Files.createTempFile("smoke", ".zip");
        Files.delete(zip);
        try (FileSystem fs = FileSystems.newFileSystem(zip, Map.of("create", "true"))) {
            System.out.println("zipfs ok: " + fs.provider().getScheme());
        }

        ManagementFactory.getPlatformMBeanServer();
        System.out.println("jmx ok");

        System.out.println("sql ok: " + java.sql.Types.class.getName());
    }
}

Run it with the runtime you built:

Shell
/opt/runtime/bin/java -cp . RuntimeSmokeTest.java

If jdk.crypto.ec is missing, the TLS line fails with a handshake error against any server that insists on an elliptic-curve suite. Treat a passing smoke test as necessary and not sufficient: your own integration tests against the final image are what cover the rest, so run them against the image you ship and not against the build container.

Measure before and after

The reason to do this is size, so record it. Build both images and compare the layers that differ:

Shell
docker build -f Dockerfile.jre  -t shop:jre  .
docker build -f Dockerfile.jlink -t shop:jlink .
docker images shop --format '{{.Tag}}  {{.Size}}'
docker history shop:jlink --format '{{.Size}}  {{.CreatedBy}}' | head -5

Write both numbers in the pull request, along with the cold start time of each. A runtime that saves 100 MB per image on a fleet that pulls images hundreds of times a day pays for itself, and one that saves 30 MB on a single internal service does not repay the maintenance.

Faster startup with a CDS archive

jlink can add a class data sharing archive of the JDK's own classes to the image, which trims startup:

Shell
jlink --add-modules "${MODULES},${EXTRAS}" \
      --strip-debug --no-man-pages --no-header-files --compress=zip-6 \
      --generate-cds-archive \
      --output /opt/runtime

The archive is built for exactly this runtime, so it is valid only for the image you generate it in. For your application's classes, Spring Boot and the JDK have a separate application class data sharing flow, covered in the framework documentation for your version. Keep the two ideas apart: the JDK archive comes free with jlink, and the application archive is a second step with its own training run.

Where this does not apply

Applications on the classpath without modules work fine with jlink, which operates on the JDK's modules and includes your jar separately. Libraries that need the full JDK tooling at runtime (some APM agents, attach APIs) require the jdk.attach module. The [jlink reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/jlink.html) and the [jdeps reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/jdeps.html) are the primary sources.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.