Setting Java Heap Size Inside a Docker Container

Fredrik Fischer
Nordnet Tech
Published in
5 min readSep 22, 2023

--

Photo by Venti Views on Unsplash

Running Java applications in a container might seem like a trivial task, but there are some pitfalls that can cause problems in production. This article will explain how to set the Java Heap Size inside a Docker container.

Virtual memory used by a Java process extends far beyond just Java Heap. JVM includes many subsystems:

  • Garbage Collector
  • Class Loading
  • JIT compilers etc

all these subsystems require certain amount of RAM to function. JVM is not the only consumer of RAM. Native libraries (including standard Java Class Library) may also allocate native memory. And this won’t be even visible to Native Memory Tracking. Java application itself can also use off-heap memory by means of direct ByteBuffers.

In short JVM needs additional memory (code cache, off-heap, thread stacks, GC data structures..), as does the operating system.

Problem Statement

When running Java in a container and using the heap memory as an indicator for the memory consumption there is a risk that the JVM application gets killed due to that the container running the JVM allocates more memory than the memory requested from Kubernetes.

How does this happen?

--

--