Java in a container
Container-aware JVM, heap as a percentage, CPU quotas and thread pools, layered jars, and startup time.
A JVM asks the machine how much memory and how many CPUs it has, and sizes its heap and its thread pools from the answers. In a container the machine lies, or rather the container runtime tells the truth through a mechanism — cgroups — that older JVMs did not read. The result was a generation of services that were killed by the kernel for using memory they thought they had. Modern Java reads cgroups correctly; the settings that follow from that are what this lesson is about.
The JVM and cgroups
A container's memory limit and CPU quota are cgroup settings the kernel enforces. Java 10 (and 8u191) taught the JVM to read them: Runtime.availableProcessors() returns the CPU quota rounded up, not the host's core count, and the default heap size is a fraction of the container's limit, not the host's RAM. java -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|ActiveProcessorCount' inside the container is how you check what it decided.
The kernel enforces the memory limit on the whole process, not the heap. A JVM's footprint is the heap plus Metaspace, the code cache, thread stacks, direct buffers, GC data structures and the native allocator's overhead — the memory-areas lesson measured each one. Set the heap to the container limit and the process exceeds the limit the first time Metaspace grows, and the kernel's answer is OOMKilled, exit code 137, with nothing in the Java log because there was no Java exception.
MaxRAMPercentage, not -Xmx
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-XX:InitialRAMPercentage=50.0", "-jar", "app.jar"]-XX:MaxRAMPercentage sizes the heap as a fraction of the container's memory limit, so one image serves every size of container. At a 1 GiB limit the heap is 768 MiB, and the other quarter is for everything else. At 4 GiB the heap is 3 GiB.
The default is 25%, a heap a quarter the size of the container. That is right for a laptop shared with an IDE, and wrong for a container that exists to run this one process. 75% is the usual starting point for a service. Go lower if it uses direct buffers heavily (Netty, Kafka clients) or runs many threads.
-Xmx still works and pins the heap regardless of the limit. It is the right choice when you want the number to be explicit and the container is sized to it. This repository's API runs under systemd rather than in a container, with -Xmx384m and a MemoryMax=1G on the unit. It is the same shape with the same reasoning in its comments: the heap cannot grow past the flag, so the extra room is for non-heap growth under load.
Whichever you use, -XX:+ExitOnOutOfMemoryError makes a heap exhaustion end the process so the orchestrator restarts it, rather than leaving a JVM that answers health checks and nothing else.
CPU: the quota, and what the pools see
A container with a CPU limit of 2 is not two cores; it is a quota — 200 ms of CPU time per 100 ms period, across however many cores it happens to run on. A JVM with the limit reads availableProcessors() == 2, and sizes from that: the common ForkJoinPool gets one worker, the G1 collector gets two threads, Tomcat's default of 200 request threads stays 200 because it never asked. Two consequences to check:
- A fractional limit rounds up.
cpu: 500misavailableProcessors() == 1, soparallelStream()is sequential and the JIT compiler threads share one CPU with the application, which makes the warm-up in the JIT lesson painfully slow. Give a JVM at least one whole CPU, and prefer a request without a limit where the platform allows it — throttling a JVM at its quota produces latency spikes that look like GC pauses and are not. - Pools sized from cores are sized from the quota. A
newFixedThreadPool(availableProcessors())in a500mcontainer is one thread. Size I/O pools from the downstream's capacity, as the executors lesson says, not from CPU count; and set-XX:ActiveProcessorCount=Nonly when you have measured that the JVM's guess is wrong.
Spring Boot layered jars
A fat jar changes entirely when one class changes, so every deploy pushes and pulls 40 MB. Spring Boot's layered jar splits it by rate of change, and the Dockerfile copies each part as its own layer:
FROM eclipse-temurin:21-jdk AS build
# ... build as in the last lesson, then:
RUN java -Djarmode=tools -jar target/app.jar extract --layers --destination extracted
FROM eclipse-temurin:21-jre-jammy
WORKDIR /app
COPY --from=build /src/extracted/dependencies/ ./
COPY --from=build /src/extracted/spring-boot-loader/ ./
COPY --from=build /src/extracted/snapshot-dependencies/ ./
COPY --from=build /src/extracted/application/ ./
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "org.springframework.boot.loader.launch.JarLauncher"]Dependencies change when the POM does; the application layer changes every commit and is a few hundred kilobytes. A deploy that changed only code pushes only that layer, and a node that already has the dependency layer pulls only that layer. (-Djarmode=layertools is the Boot 2 and 3.2 spelling of the same command.) Class Data Sharing, -XX:SharedArchiveFile from a training run in the build, is the next step for startup time; Boot 3.3+ can produce the archive during extract.
Health checks, signals and startup
The orchestrator needs to know two things the process must tell it.
- Is it alive? Use a
HEALTHCHECKin the Dockerfile, or a liveness probe in Kubernetes, hitting Actuator's/actuator/health/liveness. - Is it ready for traffic? This is a different question, which the Actuator lesson separated. A JVM that is up and still warming its connection pool is alive and not ready.
Point the two probes at the two endpoints. Give the startup probe or initialDelaySeconds enough room for a Spring Boot start on a throttled CPU, which is longer than on your laptop.
Shutdown is the same contract in reverse. The orchestrator sends SIGTERM, waits a grace period, then ends the process outright.
Java handles SIGTERM by running shutdown hooks. Spring Boot's server.shutdown=graceful with spring.lifecycle.timeout-per-shutdown-phase=20s finishes in-flight requests first. But this happens only if Java is PID 1 or is forwarded the signal. That is why the exec-form ENTRYPOINT matters, and why a sh -c "java ..." wrapper loses requests on every deploy.
Under the hood: how a JVM that used to guess wrong learned to read cgroups
The kubernetes course's resource lesson covers what a CPU limit and a memory limit become at the kernel level, for any process: a CFS quota and a hard memory ceiling. What is specific to Java is the layer above that. For years, the JVM did not consult those kernel mechanisms at all. The fix was a real, gradual engineering effort inside OpenJDK. It is worth understanding precisely, because a service can still run on a JVM old enough to have the bug.
The original problem: ergonomics that predate containers
Before container awareness existed, the JVM sized itself from /proc/meminfo and /proc/cpuinfo, the host's total memory and core count. That was the only notion of "the machine" Linux offered a userspace process. It was a correct assumption on bare metal and inside a VM, where the kernel a process talks to really does own the whole machine's resources.
A cgroup changes what the kernel will actually grant a process, but it does not change what /proc/meminfo reports inside that cgroup by default. So a JVM in a container with a 512 MiB memory limit, running on a 64 GiB host, read 64 GiB. It defaulted its heap to a quarter of that (roughly 16 GiB by the pre-container default), and allocated objects until the cgroup's hard ceiling arrived and the kernel's OOM killer ended the process.
That is the exact OOMKilled, exit 137 this lesson's main text describes. Here the root cause was never a leak or an undersized limit. It was a JVM sizing itself off a number that was never true for it.
Container awareness: reading /sys/fs/cgroup instead of /proc
The fix was for the JVM's ergonomics code to check the cgroup filesystem for a memory and CPU limit, and use that instead of the host's totals when one is present and tighter than the host's real resources. (Ergonomics is the logic that picks default heap size, GC thread counts and availableProcessors() before any user flag is applied. The files are /sys/fs/cgroup/memory/... under cgroup v1, and /sys/fs/cgroup/memory.max and friends under v2.)
This landed in OpenJDK behind the flag -XX:+UseContainerSupport. It became the default (no flag needed) starting with Java 10, backported to 8u191. Hedge on that detail if you are reading it from a specific JDK's release notes, since exact backport point-releases for older 8 update trains are easy to misremember. The "10, and 8u191 backward" shape is the well-documented headline.
A JVM built before that point silently uses the host's numbers no matter what limit the container declares. -XX:+PrintFlagsFinal -version | grep -i UseContainerSupport (present and true on any current JDK) is how you confirm a given image's JVM has the awareness at all. Cross-checking MaxHeapSize against the container's real memory limit is how you confirm it decided sensibly.
cgroup v2's unified hierarchy (the now-common layout, /sys/fs/cgroup/memory.max rather than v1's split memory/ and cpu/ trees) needed its own JDK-side support to read correctly. That landed across subsequent JDK releases as v2 adoption grew across distributions. This is another detail to verify against the specific JDK you are deploying, not assume.
What "container-aware" actually computes
Awareness is not one number. It is three independent readings feeding three independent defaults:
- The memory limit feeds
MaxRAMPercentage's base (this lesson's main text). - The CPU quota feeds
Runtime.availableProcessors(), rounded up to the nearest whole core count from a fractional quota. Socpu: 500mstill reports1, never0. - That processor count, in turn, seeds every ergonomic default that reads it at JVM startup: G1's worker-thread count, the common
ForkJoinPool's parallelism, and the JIT compiler-thread count.
This is why a container sized well below one core produces a JVM that is not just throttled by the kernel, but has already configured itself for a single-core machine.
Try it yourself
Reason through a mis-sized heap on an old JVM
A service runs eclipse-temurin:8u181-jre (a build that predates 8u191) inside a container with a 512 MiB memory limit, on a Kubernetes node with 64 GiB of physical RAM. No -Xmx or -XX:MaxRAMPercentage flag is set. The team is relying on JVM defaults, as -XX:MaxRAMPercentage=75 recommends doing only on a container-aware JVM.
Using the mechanism above (what container awareness actually reads, and what happens when it is absent), predict:
- Roughly what the JVM sizes its default heap to.
- What kills the process, and how it will look in
kubectl describe podversus the Java process's own logs.
Why an old JVM sizes itself off the node, not the container
Without container awareness, the JVM's ergonomics never look at the cgroup at all. It reads /proc/meminfo, sees the node's 64 GiB, and defaults the heap to its pre-container fraction of that (roughly a quarter, so on the order of 16 GiB), entirely independent of the container's 512 MiB limit.
The JVM does not fail immediately. It starts, and its heap grows lazily as the application allocates, so the process runs normally at first. The moment total process memory (heap plus everything else) crosses 512 MiB, the kernel, not the JVM, enforces the cgroup's hard ceiling and sends SIGKILL to the process. There is no Java exception, no stack trace and nothing in the application log, because the JVM was never told it was approaching a limit it didn't know existed.
kubectl describe pod shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137, which is the kernel's record. The Java process's own logs simply stop, mid-request, with nothing explaining why. The fix is not a bigger limit. It is a JDK new enough to read the limit that was already correct.
Misconceptions
- "A newer JDK always means the JVM is reading the container's limits correctly." Awareness became the default at 8u191/Java 10. But one mechanism inside it, reading cgroup v2's unified layout rather than v1's split hierarchy, needed its own JDK-side support as v2 became the common default across Linux distributions. A JDK new enough for basic
UseContainerSupportis not automatically new enough to have been tested against whichever cgroup version a given host actually runs. CheckingMaxHeapSizeagainst the real limit, on the actual base image, is the only way to be sure, not the JDK's major version number alone. - "The container limit and the JVM's heap limit are the same number." They never should be. The cgroup memory limit bounds the whole process: heap, Metaspace, thread stacks, direct buffers and the native allocator.
MaxRAMPercentageexists precisely to leave room for everything the JVM needs that is not heap. Setting the heap to the full container limit guarantees an eventualOOMKilledthe first time any non-heap area grows, regardless of how container-aware the JVM is.
Sources
- OpenJDK, JDK-8146115 ("Improve docker container detection and resource configuration usage") — the enhancement that introduced cgroup-aware ergonomics, delivered in JDK 10 and backported to 8u191.
- Oracle / OpenJDK release notes for JDK 8 update 191 and JDK 10 — the
-XX:+UseContainerSupportdefault and what it changed. - Red Hat, "Java on Kubernetes" / OpenJDK container-awareness documentation — cgroup v1 versus v2 support and what each ergonomic default reads (name given without a specific URL; verify the current location before citing).