Video in progress

What problems are there in the JVM settings of this Dockerfile?

FROM eclipse-temurin:21-jre
COPY app.jar /app/app.jar
# pod limit: 2Gi
ENV JAVA_OPTS="-Xms2g -Xmx2g -XX:+UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError"
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar /app/app.jar"]

The heap equals the container limit, so there is no room for native memory and the pod gets OOMKilled. Because exec is missing, the JVM isn't PID 1 and doesn't receive SIGTERM, and the GC log and dumps are lost together with the container.

📖 Answer

There are four problems.

-Xmx2g with a 2Gi limit. The heap takes the whole limit, leaving no room for metaspace, thread stacks, the code cache and GC structures. The result is the kernel OOM killer, exit code 137 and no Java error at all.

-XX:+UseConcMarkSweepGC. CMS was removed in JDK 14. JDK 21 won't start with this flag: Unrecognized VM option. That means this image doesn't work at all, so someone never tried it.

sh -c without exec. PID 1 is the shell, and Java is its child. When Kubernetes sends SIGTERM, the shell doesn't pass it to Java, graceful shutdown doesn't work, and after 30 seconds SIGKILL arrives. In-flight requests are cut off.

The dump and log path. HeapDumpPath isn't specified, so the dump is written to the working directory and is lost when the pod is recreated. There is no GC log at all.

The fixed version:

FROM eclipse-temurin:21-jre
COPY app.jar /app/app.jar
ENV JAVA_OPTS="-XX:MaxRAMPercentage=70 -XX:+ExitOnOutOfMemoryError \
  -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps \
  -Xlog:gc*:file=/logs/gc.log:time,uptime:filecount=5,filesize=20m"
ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar /app/app.jar"]

Volumes are mounted at /dumps and /logs. The image should also run as a non-root user, but that is a different topic.

In practice such mistakes aren't in one Dockerfile but in dozens of copies. That is why a common base image and a lint in CI give more benefit here than a separate code review.