Naturally, the universal Java Virtual Machine (JVM) fine-tuning principles are applicable to Tomcat too. While the JVM tuning is a whole science of itself, there are some basic, good practices which anyone can easily apply:
- The maximum heap size,
Xmx, is the maximum memory Tomcat can use. It should be set to a value which leaves enough free memory for the Droplet itself to run and any other services you may have on the Droplet. For example, if your Droplet has 2 GB of RAM, then it might be safe to allocate 1GB of RAM to xmx. However, please bear in mind that the actual memory Tomcat uses will be a little bit higher than the size of
- The minimal heap size,
Xms, is the amount of memory allocated at startup. It should be equal to the xmx value in most cases. Thus, you will avoid having the costly memory allocation process running because the size of the allocated memory will be constant all the time.
- The memory where classes are stored permanently,
MaxPermSize, should allow Tomcat to load your applications’ classes and leave spare memory from the
Xmxvalue for the instantiation of these classes. If you are not sure how much memory your applications’ classes require, then you could set the
MaxPermSizeto half the size of
Xmxas a start — 512 MB in our example.
On Ubuntu 14.04 you can customize Tomcat’s JVM options by editing the file
/etc/default/tomcat7. So, to apply the above tips please open this file with your favorite editor:
- sudo nano /etc/default/tomcat7
If you have followed Tomcat’s installation instructions from the prerequisites you should find the following line:
... JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -Djava.awt.headless=true -Xmx512m -XX:MaxPermSize=256m -XX:+UseConcMarkSweepGC" ...
Provided your Droplet has 2 GB of RAM and you want to allocate around 1 GB to Tomcat, this line should be changed to:
... JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -Djava.awt.headless=true -Xms1024m -Xmx1024m -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC" ...
For this setting to take effect, you have to restart Tomcat:
- sudo service tomcat7 restart
The above JVM configuration is a good start, but you should monitor Tomcat’s log (
/var/log/tomcat7/catalina.out) for problems, especially after restarting Tomcat or doing deployments. To monitor the log use the
tail command like this:
- sudo tail -f /var/log/tomcat7/catalina.out
If you are new to
tail, you have to press the key combination
Ctrl-C on your keyboard to stop tailing the log.
Search for errors like
OutOfMemoryError. Such an error would indicate that you have to adapt the JVM settings and more specifically increase the
That’s it! Now you have secured and optimized Tomcat in just a few easy-to-follow steps. These basic optimizations are recommended, not only for production, but even for test and development environments which are exposed to the Internet.