Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 111 ยท Language Recipes

Containerizing a Java App

Containerize a Java app with a multi-stage build, a JRE runtime image, correct JVM memory flags, Maven and Gradle caching, Spring Boot layers and jlink.

Java and containers had a rocky start, because early JVMs looked at the host's memory and CPUs and ignored the container's limits. Modern JVMs (since Java 10, and in all current long-term-support releases) understand cgroups, and the official images are well maintained, so containerizing Java is now straightforward. The remaining traps are different: shipping a full JDK and Maven to production, sizing the heap, and rebuilding every dependency whenever one source file changes.

This lesson builds a small Java 21 web service into an image step by step. To keep the walkthrough runnable with nothing but a JDK, the example uses only the JDK's built-in HTTP server, compiled with javac; the Maven and Gradle versions of the same Dockerfile are shown as read-only examples because they would download hundreds of megabytes of build tools. All other output comes from real builds on Docker 29 with the Eclipse Temurin images.

The app

One class, no dependencies. It answers / with information about the JVM it runs in (this will be useful later) and /healthz with ok:

Java
package demo;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class App {
    public static void main(String[] args) throws IOException {
        int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/", exchange -> {
            long maxMb = Runtime.getRuntime().maxMemory() / (1024 * 1024);
            byte[] body = ("{\"message\":\"Hello from a container\",\"cpus\":"
                    + Runtime.getRuntime().availableProcessors()
                    + ",\"maxHeapMb\":" + maxMb + "}").getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().add("Content-Type", "application/json");
            exchange.sendResponseHeaders(200, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.createContext("/healthz", exchange -> {
            byte[] body = "ok".getBytes(StandardCharsets.UTF_8);
            exchange.sendResponseHeaders(200, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("shutting down")));
        server.start();
        System.out.println("listening on " + port);
    }
}

The file lives at src/main/java/demo/App.java. The shutdown hook runs when the JVM receives SIGTERM, which is how Java handles graceful shutdown: you register hooks, and the JVM runs them on exit. Frameworks like Spring Boot do this for you.

JDK to build, JRE to run

A JDK contains the compiler and tools (javac, jar, jlink); a JRE has only what is needed to run programs. Production does not need a compiler, so a multi-stage build uses the JDK in the first stage and a JRE in the second:

DOCKERFILE
# syntax=docker/dockerfile:1
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /src
COPY src ./src
RUN mkdir -p out \
 && javac -d out $(find src -name '*.java') \
 && printf 'Main-Class: demo.App\n' > manifest.txt \
 && jar --create --file app.jar --manifest manifest.txt -C out .

FROM eclipse-temurin:21-jre-alpine AS runtime
RUN addgroup -S app && adduser -S -G app -u 10001 app
WORKDIR /app
COPY --from=build /src/app.jar app.jar
USER app
EXPOSE 8080
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s \
  CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
ENTRYPOINT ["java", "-jar", "app.jar"]

Build it and run it with limits:

CONSOLE
$ docker build -t java-app:1 .
$ docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}' | grep java-app
java-app:1 286MB
$ docker run -d --name jv -m 256m --cpus 2 -p 127.0.0.1:8080:8080 java-app:1
$ curl -s localhost:8080/
{"message":"Hello from a container","cpus":2,"maxHeapMb":185}
$ docker ps --filter name=jv --format '{{.Status}}'
Up 11 seconds (healthy)
$ docker logs jv
Picked up JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=75
listening on 8080

A few points about this Dockerfile:

  • Alpine's Temurin images exist for Java 21 and are a good default. Use the Debian/Ubuntu-based tags (21-jre) if you need glibc for native libraries.
  • Non-root: Alpine uses addgroup -S and adduser -S instead of useradd; the app runs as UID 10001 (Users and Permissions).
  • The health check uses wget, which BusyBox provides on Alpine. The JRE image has no curl.
  • ENTRYPOINT in exec form makes java PID 1, so it gets SIGTERM. Stopping the container ran the shutdown hook:
CONSOLE
$ time docker stop jv
jv

real    0m3.0s
$ docker logs jv | tail -2
listening on 8080
shutting down

The -m 256m --cpus 2 flags in the run command are the key to the next section.

JVM memory in containers

The JVM sizes its maximum heap as a percentage of available memory. In a container, "available" means the cgroup limit (-m), if there is one. The default is 25%, which is conservative: the rest is left for metaspace, thread stacks, buffers and the garbage collector. Ask the JVM what it decided, with different limits:

CONSOLE
$ docker run --rm -m 256m -e JAVA_TOOL_OPTIONS= --entrypoint java java-app:1 -XX:+PrintFlagsFinal -version | grep -E ' MaxHeapSize'
   size_t MaxHeapSize          = 132120576      {product} {ergonomic}
$ docker run --rm -m 1g -e JAVA_TOOL_OPTIONS= --entrypoint java java-app:1 -XX:+PrintFlagsFinal -version | grep -E ' MaxHeapSize'
   size_t MaxHeapSize          = 268435456      {product} {ergonomic}
$ docker run --rm -m 256m --entrypoint java java-app:1 -XX:+PrintFlagsFinal -version | grep -E ' MaxHeapSize'
   size_t MaxHeapSize          = 201326592      {product} {ergonomic}

Reading the three results:

  • With a 1 GiB limit and the default 25%, the heap is 268,435,456 bytes: exactly 256 MiB.
  • With a 256 MiB limit and the default, the heap is 132,120,576 bytes (126 MiB), more than 25%. For small memory sizes the JVM applies a floor so the heap is not uselessly tiny.
  • With -XX:MaxRAMPercentage=75 (our JAVA_TOOL_OPTIONS) and a 256 MiB limit, the heap is 201,326,592 bytes: 192 MiB. The app reported 185 MB, because one of the survivor spaces is not counted as usable.

For a container that runs only the JVM, -XX:MaxRAMPercentage=75 is a sensible starting point: three quarters of the limit for the heap, a quarter for everything else. Do not go to 90%; the process also needs memory outside the heap and exceeding the limit ends with the kernel's OOM killer (Resource Limits). Prefer a percentage to a fixed -Xmx, because the percentage follows the limit when someone changes it.

JAVA_TOOL_OPTIONS is read by every JVM that starts, and prints the Picked up ... line you saw. That makes it a convenient way to configure the JVM without changing the command, and the Picked up line is harmless. Alternatively put flags in the ENTRYPOINT.

CPUs

The JVM also uses the CPU limit to size its thread pools and garbage collector. With --cpus 2, the app above reported "cpus":2. Without a limit it sees every host core, which is what docker run without --cpus gives you:

CONSOLE
$ docker run --rm --entrypoint sh java-app:1 -c 'java -XshowSettings:system -version 2>&1 | head -5'
Picked up JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=75
Operating System Metrics:
    Provider: cgroupv2
    Effective CPU Count: 6
    CPU Period: 100000us

Provider: cgroupv2 confirms the JVM is reading the container's cgroup. Remember that a container with fewer than 2 CPUs or less than about 1.8 GB of memory can make the JVM choose the serial garbage collector, which is fine for small services but surprising if you expected G1.

A container with no memory limit makes the JVM use a percentage of the host's memory. In our jlink test below, a container with no -m printed "maxHeapMb":8936, three quarters of the whole machine. Always set a memory limit for Java containers, in Compose or on docker run.

Caching dependencies with Maven and Gradle

Real projects use a build tool. The principle is the same as for npm and pip: copy the dependency descriptor, resolve dependencies, then copy the source. These are read-only examples (they need Maven or Gradle images and network downloads), shown so you can adapt them.

DOCKERFILE
# Maven (read-only example)
# syntax=docker/dockerfile:1
FROM maven:3-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
RUN --mount=type=cache,target=/root/.m2 \
    mvn -q -B dependency:go-offline
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 \
    mvn -q -B package -DskipTests

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=build /src/target/app.jar app.jar
USER 10001
ENTRYPOINT ["java", "-jar", "app.jar"]
DOCKERFILE
# Gradle (read-only example)
# syntax=docker/dockerfile:1
FROM gradle:8-jdk21 AS build
WORKDIR /src
COPY build.gradle settings.gradle ./
RUN --mount=type=cache,target=/home/gradle/.gradle \
    gradle --no-daemon dependencies > /dev/null
COPY src ./src
RUN --mount=type=cache,target=/home/gradle/.gradle \
    gradle --no-daemon bootJar -x test

The first RUN depends only on the build file, so it is cached until your dependencies change. The cache mount (/root/.m2 for Maven) keeps downloaded artifacts between builds even when they do change (Build Performance). Run tests in a separate stage or CI job, not in the image build for production (Docker in CI).

Spring Boot layers (read-only example)

A Spring Boot "fat jar" bundles your code and every library into one file. If you copy that jar in one layer, a one-line code change rewrites the whole layer, often 50 MB or more, and every deploy pushes it again. Spring Boot can split the jar into layers (dependencies, Spring Boot loader, snapshot dependencies, application), so only the small application layer changes. A sketch for recent Spring Boot versions:

DOCKERFILE
FROM eclipse-temurin:21-jdk-alpine AS extract
WORKDIR /src
COPY target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination extracted

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=extract /src/extracted/dependencies/ ./
COPY --from=extract /src/extracted/spring-boot-loader/ ./
COPY --from=extract /src/extracted/snapshot-dependencies/ ./
COPY --from=extract /src/extracted/application/ ./
USER 10001
ENTRYPOINT ["java", "-jar", "app.jar"]

The order puts the least-changing layer first, which is the same rule as everywhere else. Exact commands and folder names have changed across Spring Boot versions, so check the documentation for yours. Spring Boot also has a built-in image builder (mvn spring-boot:build-image, using Cloud Native Buildpacks) that produces layered, memory-tuned images without a Dockerfile; it is worth knowing about even if you prefer Dockerfiles for control.

The Java 21 JRE image is 286 MB, of which your application is a few kilobytes. jlink builds a custom runtime that contains only the Java modules your program uses. jdeps finds which modules those are. Do it in the build stage and copy the result onto a plain Alpine base:

DOCKERFILE
# syntax=docker/dockerfile:1
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /src
COPY src ./src
RUN mkdir -p out \
 && javac -d out $(find src -name '*.java') \
 && printf 'Main-Class: demo.App\n' > manifest.txt \
 && jar --create --file app.jar --manifest manifest.txt -C out .
RUN jdeps --print-module-deps --ignore-missing-deps app.jar > modules.txt \
 && cat modules.txt \
 && jlink --add-modules "$(cat modules.txt)" \
          --strip-debug --no-header-files --no-man-pages \
          --compress zip-6 --output /opt/runtime

FROM alpine:3.22 AS runtime
RUN apk add --no-cache libstdc++ \
 && addgroup -S app && adduser -S -G app -u 10001 app
COPY --from=build /opt/runtime /opt/runtime
COPY --from=build /src/app.jar /app/app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["/opt/runtime/bin/java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]

The build prints the modules jdeps found, and the result is dramatically smaller:

CONSOLE
$ docker build -f Dockerfile.jlink -t java-app:jlink --progress=plain .
...
#13 3.421 java.base,jdk.httpserver
$ docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}' | grep java-app
java-app:jlink 79.8MB
java-app:1 286MB
$ docker run --rm --entrypoint /opt/runtime/bin/java java-app:jlink --list-modules
java.base@21.0.12.1
jdk.httpserver@21.0.12.1

Just two modules, and 79.8 MB against 286 MB. The custom runtime serves requests as before. The trade-offs are real, though: you must rebuild the runtime to pick up JVM security patches, jdeps can miss modules that are loaded reflectively (frameworks like Spring and JDBC drivers often need extra --add-modules), and the standard JRE image is easier to keep updated. Use jlink when image size matters, such as many small services or constrained pulls, not as a default.

Common problems

  • OutOfMemoryError or exit code 137. Exit 137 is the OOM killer (the container exceeded its limit); a Java OutOfMemoryError is the heap being too small. Raise the memory limit, or lower MaxRAMPercentage if the container is killed.
  • Slow start-up. JVM warm-up takes seconds. Give the health check a generous start_period, and do not set aggressive restart rules.
  • Wrong time zone or locale. Slim images are minimal; set TZ or -Duser.timezone explicitly.
  • Out-of-date base image. Rebuild regularly for JVM security fixes and scan images (Image Security and Scanning).
  • Running mvn package in the image build with tests. Slow builds and no cache benefit; separate tests into CI.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a multi-stage Java Dockerfile use a JDK image for the build stage and a JRE image for the runtime stage?

    The JDK has javac, jar, jlink and other tools that are needed only to build. The JRE has just what is needed to run, so the final image is smaller.
  2. 2. A container runs with -m 1g and no JVM flags. What is the maximum heap in our test?

    The JVM reads the cgroup limit and applies MaxRAMPercentage, 25% by default. The test printed 268435456 bytes, which is 256 MiB.
  3. 3. What is the risk of running a Java container with no memory limit and -XX:MaxRAMPercentage=75?

    Without a cgroup limit the JVM sees the host's memory. Always set a limit with -m or deploy.resources.limits.memory so the heap follows it.
  4. 4. What does jlink do in a Dockerfile build stage?

    With the modules found by jdeps, jlink builds a minimal runtime image directory. In our test it cut the image from 286 MB to 79.8 MB.
  5. 5. Why use ENTRYPOINT ["java", "-jar", "app.jar"] (exec form) instead of a shell-form command?

    In shell form the process is a child of /bin/sh -c, and the shell may not pass signals on. In exec form Java is PID 1 and docker stop triggers its shutdown hooks.

Summary

  • Build with a JDK in one stage, run with a JRE (or a jlink runtime) in the next; the app image was 286 MB with the JRE and 79.8 MB with jlink.
  • Use ENTRYPOINT in exec form so java is PID 1 and shutdown hooks run on docker stop; run as a non-root user.
  • Modern JVMs honor container limits. The default maximum heap is 25% of the memory limit; -XX:MaxRAMPercentage=75 is a good start for a single-JVM container, and JAVA_TOOL_OPTIONS sets flags without changing the command.
  • Always set a memory limit, otherwise the JVM sizes itself from the host's memory.
  • For Maven and Gradle, copy the build file first, resolve dependencies in a cached layer with a cache mount, then copy the source (read-only examples).
  • Spring Boot layered jars keep the frequently changing application code in a small layer.
  • Use jdeps and jlink for the smallest images, remembering that you take over patching the runtime.

Next: Containerizing Go and Rust Apps