Sub topic 11
Sizing the JVM for containers
This chapter assumes you can build a Spring Boot JAR, write a basic Dockerfile, and read a Kubernetes or docker run resource limit. It covers how the JVM sees memory and CPU inside a container, how to set heap size, and the errors you are most likely to hit.
Why containers change the sizing problem
On a plain server, the JVM sees the whole machine. In a container, the operating system enforces limits through Linux control groups (cgroups). A cgroup is a kernel feature that caps the memory and CPU a group of processes can use.
Two things can go wrong:
- The JVM sizes itself from the wrong number and picks a heap that is too large or too small.
- The process uses more memory than the limit allows, and the kernel kills it.
Modern JVMs (Java 11 and later, and Java 8 from update 191) read cgroup limits. The eclipse-temurin:21-jre image from the earlier Dockerfile chapter is container-aware, so you do not need old flags such as -XX:+UseCGroupMemoryLimitForHeap.
What counts toward container memory
The heap is only part of the JVM's memory use. The container limit applies to everything the process allocates.
| Area | What it holds | Controlled by |
|---|---|---|
| Heap | Your objects | `-Xmx`, `-XX:MaxRAMPercentage` |
| Metaspace | Class metadata | `-XX:MaxMetaspaceSize` (unbounded by default) |
| Thread stacks | One stack per thread | `-Xss`, thread count |
| Code cache | JIT-compiled code | `-XX:ReservedCodeCacheSize` |
| Direct buffers | NIO and Netty buffers | `-XX:MaxDirectMemorySize` |
| Native overhead | GC structures, libraries, the JVM itself | Not directly controlled |
If you set the heap to 100% of the container limit, the other areas push the process over the limit. The kernel then kills it with the out-of-memory (OOM) killer. Kubernetes reports this as OOMKilled with exit code 137.
How the JVM picks a default heap
When you set no heap flag, the JVM uses a fraction of the memory it detects. The default maximum heap is 25% of available memory. In a container with a 1 GiB limit, that gives roughly a 256 MiB heap.
This default is safe but wasteful for a container that runs a single application. Three quarters of the memory stays unused.
Setting the heap with percentages
Prefer -XX:MaxRAMPercentage over a fixed -Xmx. The percentage follows the container limit, so the same image works when you change the limit in Kubernetes.
docker run --rm -m 1g -p 8080:8080 \
-e JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75.0 -XX:InitialRAMPercentage=50.0" \
myorg/myapp:1.0.0JAVA_TOOL_OPTIONS is an environment variable the JVM reads at startup. It lets you tune the JVM without changing the image's ENTRYPOINT. The JVM prints Picked up JAVA_TOOL_OPTIONS: ... to standard error when it uses it, which is a quick way to confirm the setting applied.
Choosing a percentage:
- 75% is a common starting point for containers of 1 GiB or more.
- For containers under about 512 MiB, use 50% to 60%, because the fixed non-heap overhead is a larger share.
- Use a fixed
-Xmxonly when you need a heap size that does not depend on the container limit.
Checking what the JVM decided
Do not guess. Ask the JVM what it detected.
docker run --rm -m 1g eclipse-temurin:21-jre \
java -XX:MaxRAMPercentage=75.0 -XX:+PrintFlagsFinal -version \
| grep -E "MaxHeapSize|MaxRAMPercentage|ActiveProcessorCount"MaxHeapSize is reported in bytes. For a 1 GiB limit at 75%, expect a value near 805,306,368 bytes (768 MiB).
For a running Spring Boot application with Actuator, you can read live memory numbers. The earlier chapter exposed only health and info. Expose metrics to use this, and think about who can reach it.
management.endpoints.web.exposure.include=health,info,metricsThen request /actuator/metrics/jvm.memory.max?tag=area:heap and /actuator/metrics/jvm.memory.used?tag=area:heap.
CPU limits and processor count
The JVM computes the number of available processors from the container's CPU limit. A limit of 1.5 CPUs rounds up to 2. This number controls:
- the default garbage collector choice,
- the size of GC worker thread pools,
- the size of the common fork-join pool,
- some library defaults for thread pool sizes.
The garbage collector choice matters most. The JVM selects the Serial collector when it sees fewer than 2 processors or less than about 1792 MiB of memory. Otherwise it selects G1. A small container, for example 1 CPU and 1 GiB, therefore runs the Serial collector by default.
Serial is a reasonable choice for small containers because it has low overhead. It pauses all application threads during collection, so latency-sensitive services may notice it. You can force a collector:
java -XX:+UseG1GC -XX:MaxRAMPercentage=75.0 -jar app.jarIf you set a CPU limit lower than the real work needs, Linux throttles the process. Throttling shows up as slow requests and long GC pauses, not as errors. Symptoms to watch for are high latency at low CPU use, and a container_cpu_cfs_throttled_periods_total metric that keeps climbing.
You can override the detected count when needed:
java -XX:ActiveProcessorCount=4 -jar app.jarUse this sparingly. It hides the real limit from the JVM.
Startup is CPU-heavy
The JVM uses more CPU at startup than at steady state. It loads classes, runs the Spring context, and compiles hot code. A pod with a CPU limit of 500m may take a minute to start, while the same pod with 2 CPUs starts in 15 seconds.
This interacts with Kubernetes probes. A probe that runs before the application is ready kills a healthy but slow pod. The Kubernetes chapter covers startup probes. For now, keep in mind that a low CPU limit stretches startup time.
Putting the settings in a Dockerfile
You can bake defaults into the image and still override them at run time. Because JAVA_TOOL_OPTIONS is read from the environment, an ENV line sets the default, and docker run -e or a Kubernetes manifest replaces it.
FROM eclipse-temurin:21-jre
RUN useradd --system spring
USER spring
WORKDIR /app
COPY target/myapp-1.0.0.jar app.jar
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75.0"
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]The ENTRYPOINT uses the exec form, with a JSON array. Java then runs as process 1 and receives SIGTERM directly, which graceful shutdown needs. A shell-form entrypoint would start a shell as process 1 and the signal might never reach the JVM.
Setting limits in Kubernetes
Resource requests and limits go in the container spec. The JVM reads the limit, not the request.
resources:
requests:
memory: "1Gi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1"
env:
- name: JAVA_TOOL_OPTIONS
value: "-XX:MaxRAMPercentage=75.0"Setting the memory request equal to the memory limit is a common practice for JVM workloads. Memory cannot be reclaimed from a running process without killing it, so a predictable allocation avoids surprises when the node runs short of memory. For CPU, many teams set a request and either a higher limit or no limit, to avoid throttling. Follow your cluster's policy.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Pod shows `OOMKilled`, exit code 137 | Heap percentage too high, or large non-heap use | Lower `MaxRAMPercentage`; limit threads and direct memory |
| Java throws `java.lang.OutOfMemoryError: Java heap space` | Heap too small, or a memory leak | Raise the limit and percentage, or take a heap dump |
| Process killed with no Java error | Kernel OOM killer; the JVM never got to throw | Check `kubectl describe pod` for the termination reason |
| Heap is only 25% of the limit | No heap flag was set | Set `MaxRAMPercentage` |
| Slow requests, low CPU graphs | CPU throttling | Raise the CPU limit; check throttle metrics |
| Pod restarted during startup | Probe fired before the app was ready; CPU too low | Add a startup probe; raise the CPU limit |
The difference between the second and third rows is worth remembering. A Java OutOfMemoryError means the heap filled up inside the JVM. A kill with exit code 137 means the whole process exceeded the container limit. They have different fixes.
Diagnosing with a heap dump
To capture a heap dump when the JVM runs out of heap memory, add these flags and mount a writable volume at the dump path.
java -XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/dumps \
-XX:MaxRAMPercentage=75.0 \
-jar app.jarA heap dump is large, roughly the size of the used heap. The container's filesystem layer or an emptyDir volume must have room for it. A dump does not help with a kernel OOM kill, because the JVM is gone before it can write anything. For that case, use Native Memory Tracking with -XX:NativeMemoryTracking=summary and then run jcmd <pid> VM.native_memory summary inside the container.
A sizing procedure
- Start with a memory limit of 1 GiB and
MaxRAMPercentage=75.0. - Run a load test that matches production traffic.
- Record peak heap use after garbage collection, and the container's peak working set.
- If the working set stays well under the limit, you can lower the limit. If it comes within 20% of the limit, raise the limit.
- Set the CPU request near typical use, and test startup time under that CPU.
- Repeat after major dependency or traffic changes.
Exercise
A Spring Boot pod has a 512 MiB memory limit and runs with -Xmx512m. It restarts every few hours with exit code 137 and no Java stack trace. What is wrong, and what would you change?
Show answer
The heap alone is allowed to grow to the full container limit, and metaspace, thread stacks, the code cache and direct buffers sit on top of it. The total exceeds 512 MiB, so the kernel OOM killer ends the process before Java can throw an error, which explains the exit code 137 and missing stack trace. Remove the fixed -Xmx512m and use -XX:MaxRAMPercentage=50.0 to 60.0 for this small container, or raise the limit to 1 GiB and use 75%. Then confirm the working set under load.
Exercise
A container has a limit of 1 CPU and 1 GiB of memory, and you add no collector flags. Which garbage collector does the JVM choose, and why might you override it?
Show answer
It chooses the Serial collector, because the JVM sees fewer than 2 processors and less than about 1792 MiB of memory. Serial has low overhead but pauses all application threads during collection. If the service is latency-sensitive, you can give the container more CPU and memory, or force G1 with -XX:+UseG1GC, then test pause times.
Exercise
Why does the Dockerfile in this chapter use the exec form of ENTRYPOINT?
Show answer
The exec form starts java directly as process 1, so it receives SIGTERM from Docker or Kubernetes and can run graceful shutdown. The shell form starts a shell as process 1, and the shell may not pass the signal on to the JVM.