Video in progress

How does the JVM decide how much heap to take inside a container, and what is better to use instead of -Xmx?

A modern JVM (Java 10+, 8u191+) sees the container's cgroup limit and by default sets the heap to a quarter of the memory limit. Instead of writing -Xmx by hand, it is more convenient to give a percentage with -XX:MaxRAMPercentage.

📖 Answer

You gave the container a 1 GiB limit and set no flags. The JVM takes about 256 MiB for the heap. For many services that is far too little, and the rest of the memory sits unused.

ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-jar", "app.jar"]

Now if you raise the limit from 1 GiB to 2 GiB, the heap grows on its own, with no need to rebuild the image.

Why not 100%: memory is used outside the heap too: metaspace, thread stacks, JIT code, direct buffers. 70-80% is usually a safe limit, but for an app with many threads or one that uses Netty you will need to set it lower.

To check what the JVM actually saw:

docker exec shop-api java -XX:+PrintFlagsFinal -version | grep MaxHeapSize
# or for a running process (jcmd exists only in a JDK, a JRE image may not have it)
docker exec shop-api jcmd 1 VM.flags

Old Java 8 (updates before 191) does not see the limit and calculates from the host's memory. That is the classic reason a container gets killed by the OOM killer.