How to set Java heap size (Xms/Xmx) inside Docker container?

Solution 1:

Note that in a docker-compose.yml file - you'll need to leave out the double-quotes:

  environment:
  - JVM_OPTS=-Xmx12g -Xms12g -XX:MaxPermSize=1024m

or

  environment:
  - CATALINA_OPTS=-Xmx12g -Xms12g -XX:MaxPermSize=1024m

Solution 2:

I agree that it depends on what container you're using. If you are using the official Tomcat image, it looks like it's simple enough, you will need to pass the JAVA_OPTS environment variable with your heap settings:

docker run --rm -e JAVA_OPTS='-Xmx1g' tomcat

See How to set JVM parameters?

Solution 3:

You can also just place those settings in your image so something like the following would exist in your Dockerfile:

ENV JAVA_OPTS="-XX:PermSize=1024m -XX:MaxPermSize=512m"

Solution 4:

Update: Regarding this discussion, Java has upped there game regarding container support. Nowadays (or since JVM version 10 to be more exact), the JVM is smart enough to figure out whether it is running in a container, and if yes, how much memory it is limited to.

So, rather than setting fixed limits when starting your JVM, which you then have to change in line with changes to your container limits (resource limits in the K8s world), simply do nothing and let the JVM work out limits for itself.

Without any extra configuration, the JVM will set the maximum heap size to 25% of the allocated memory. Since this is frugal, you might want to ramp that up a bit by setting the -XX:MaxRAMPercentage attribute. Also, there is -XX:InitialRAMPercentage for initial heap size and -XX:MinRAMPercentage for containers with less than 96MB RAM.

For more information on the topic, here is an excellent overview.