20 Tips for Using Tomcat in Production
I've been working with Apache Tomcat for years and always seem to stumble upon new information related to the proper setup and configuration for a production environment. I've decided to put the instructions and tips I've collected together in one place.
So here are some helpful hints for running Tomcat in a production environment:
- If you're running on a 1.5+ JVM, add the following to your
JAVA_OPTSin catalina.sh (orcatalina.batfor Windows):CODE:-
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/j2ee/heapdumps
Then use a tool such as YourKit to analyze the heapdump file.
-
- Straight from the Tomcat documentation on Jasper 2...
When using Jasper 2 in a production Tomcat server you should consider making the following changes from the default configuration.
development - To disable on access checks for JSP pages compilation set this tofalse.
genStringAsCharArray - To generate slightly more efficient char arrays, set this totrue.
modificationTestInterval - If development has to be set totruefor any reason (such as dynamic generation of JSPs), setting this to a high value will improve performance a lot.
trimSpaces - To remove useless bytes from the response, set this totrue. - Use Tomcat's clustering/session replication capability to minimize application user impact during maintenance periods.
- Implement custom error pages to hide raw exception messages. To do this, simply add something like the following to your web.xml:
XML:
-
<error-page>
-
<error-code>404</error-code>
-
<location>/error/404.html</location>
-
</error-page>
-
- Eliminate
System.outandSystem.errstatements from application code and use a logging toolkit such as Log4J for application logging. - Leverage Tomcat's shared library directory. If you're loading several applications with several of the same library dependencies, consider moving them from the applications'
WEB-INF/libdirectory to Tomcat's shared library{catalina.home}/shared/lib. This will reduce the memory used by each application and result in smaller WAR files.
Update (comments from the user@tomcat.apache.org mailing list):The following should be considered when using the shared library directory:
a) The shared classloader is searched in last resort when looking for classes, according to http://tomcat.apache.org/tomcat-5.5-doc/class-loader-howto.html.
b) Because the classes are shared, they share configuration and singletons and if they store objects statically they will prevent your application from unloading.This is turning out to be a more controversial suggestion...
Starting with Servlet Spec 2.3 (I think) there has been an emphasis on putting everything a web app needs to run into its war file.
Shared classloaders are evil, but not as evil as the invoker servlet. With a shared loader you can easily get Singleton assumptions being wrong, class cast exceptions, versioning woes, and other issues. Saving a little perm memory just doesn't justify it.
- Tweak memory parameters. Most of the time you will want to make a change to the default settings. The best advice here is to create a development environment that matches your production environment and load test the application. While you do this you can also use a profiler to identify bottlenecks, etc.
- Remove unnecessary applications.
- Secure the Manager application. By default there are no users with the manager role. To make use of the manager webapp you need to add a new role and user into the
CATALINA_HOME/conf/tomcat-users.xmlfile.XML:-
<role rolename="manager">
-
<user username="darren" password="ReallyComplexPassword" roles="manager"></user>
-
</role>
Use a valve to filter by IP or hostname to only allow a subset of machines to connect (i.e. LAN machines). This can be configured at the Engine, Host, or Context level in the
conf/server.xmlby adding something like the following:XML:-
<!-- allow only LAN IPs to connect to the manager webapp -->
-
<!-- contrary to the current Tomcat 5.5 documation the value for 'allow' is not a regular expression -->
-
<!-- future versions may have to be specified as 192.168.1.* -->
-
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="192.168.1.*"></Valve>
-
- Strip down
server.xmlby removing comments to make it easier to read and remove connectors that you don't need. An easy way to do this is the following: RenameCATALINA_HOME/conf/server.xmltoCATALINA_HOME/conf/server-original.xmland renameCATALINA_HOME/conf/server-minimal.xmltoCATALINA_HOME/conf/server.xml. The minimal configuration provides the same basic configuration, but without the nested comments is much easier to maintain and understand. Do not delete the original file as the comments make it useful for reference if you ever need to make changes. Unless you are using Tomcat with the Apache server, comment out this line inCATALINA_HOME/conf/server.xml:XML:-
<Connector port="8009" enableLookups="false" redirectPort="8443" protocol="AJP/1.3">
-
- Split your Tomcat installation for added flexibility when it comes time to upgrade Tomcat. See the "Advanced Configuration - Multiple Tomcat Instances" section in the RUNNING.txt file of the Tomcat distribution.
- Do NOT run Tomcat as root. My previous post, "3 Ways to Run a Servlet Container on Port 80 as Non-Root", for tips.
- Precompile JSPs (at build time).
- Secure directory listings. In
CATALINA_HOME/conf/web.xml:XML:-
<servlet>
-
<servlet-name>default</servlet-name>
-
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
-
<init-param>
-
<param-name>debug</param-name>
-
<param-value>0</param-value>
-
</init-param>
-
<init-param>
-
<param-name>listings</param-name>
-
<param-value>false</param-value> <!-- make sure this is false -->
-
</init-param>
-
<load-on-startup>1</load-on-startup>
-
</servlet>
-
- If you have multi-core CPUs or more than one CPUs on your server, it might be beneficial to increase the thread pool beyond the default 250. On the other hand, if you have a slow server, decreasing the thread pool will decrease the overhead on the server.
- Monitor application applications via Tomcat MBeans. This article provides some great insight on how to do this.
- Consider JDK 1.5 or even better JDK 1.6 to take advantage of performance improvements.
Update (comments from users@tomcat.apache.org mailing list):
Note that you can gain even more performance if you recompile your "string concatenation hungry" (d="aaaa"+b+"ccc") support libaries for JDK 5+ on a multi-CPU system. This is because JDK 5 uses the non-synchronized
StringBuilderinstead of the JDK 4- synchronizedStringBuffer. And synchronization over multiple CPUs takes a few more cycles than on single CPU machines. - Use the
-serverJVM option. This enables the server JVM, which JIT compiles bytecode much earlier, and with stronger optimizations. Startup and first calls will be slower due to JIT compilation taking more time, but subsequent ones will be faster. - Use GZIP compression. Look for the service connector you wish to configure for compression and add two attributes,
compressionandcompressableMimeType. For example:XML:-
<Connector>
-
port="80"
-
maxHttpHeaderSize="8192"
-
URIEncoding="UTF-8"
-
maxThreads="150"
-
minSpareThreads="25"
-
maxSpareThreads="75"
-
enableLookups="false"
-
redirectPort="8443"
-
acceptCount="100"
-
connectionTimeout="20000"
-
disableUploadTimeout="true"
-
compression="on"
-
compressableMimeType="text/html,text/xml,text/plain,application/xml">
-
</Connector>
For more information, read the Tomcat HTTP Connector documentation.
-
- The default Tomcat configuration provides good protection for most requirements, but does not prevent a malicious application from compromising the security of other applications running in the same instance. To prevent this sort of attack, Tomcat can be run with a Security Manager enabled which strictly controls access to server resources. Tomcat documentation has a good section on enabling the Security Manager.
Who's Using Tomcat in Production
Curious about what other organizations run Tomcat in a production environment? The Tomcat wiki has a list.
20 consejos para usar Tomcat en entornos de producción
En entornos de producción con diferentes aplicativos suelen aparecer verdaderos problemas de rendimiento con el tommy, en este blog enumeran los consejos(muy elementales) para tener una vida feliz con este servidor…
meneame.net
21 Aug 07 at 8:11 am
2. Beware, the Jasper2 “trimSpaces” directive is buggy as hell (Tomcat 5.5.23 and 6.0.13)! It eats significant HTML spaces, ruining your design. I wouldn’t use it if I were you…
14. Secure directory listings.
This is done by default starting with Tomcat 5.5.13
16. Monitor applications (shameless plug)
Also check out my own fantastic monitoring utility: MessAdmin http://messadmin.sourceforge.net
To install it for your whole tomcat, put the jars in $CATALINA_HOME/common/lib/, the administration webapp in $CATALINA_HOME/webapps/, and patch $CATALINA_HOME/conf/web.xml
Now all your applications are monitored from a single location!
Cédrik
23 Aug 07 at 6:22 am
hi there,
Nice list.
I’ve helped put and support 3 apps into production with Tomcat. Many of the suggestions you’ve mentioned are good.
Do you want to add log file generation and valves (for debugging) to this as well ?
Siimilarly, you might want to add a note on “chunked encoding”.
BR,
~A
Anjan Bacchu
23 Aug 07 at 10:38 am
[...] Si utilizas Tomcat en algún entorno de trabajo serio e sposible que te interesen estos 20 consejos … [...]
Emilio-Jose Rodríguez García » 20 consejos para usar Tomcat
23 Aug 07 at 8:31 pm
I would add “start the application server with garbage collection logging enabled”, as we do for most of our production application servers (tomcat or not), and some tweaking for gc parameters (such as activating parallel and concurrent collectors).
Davide Baroncelli
24 Aug 07 at 3:58 am
nice tips
thanks for the tips, if possible please add up some tips for clustering in specific.
Nagesh
28 Aug 07 at 12:44 am
Hi,
Great tip list!
I noticed that the executor configuration was left out. This lets various tomcat connectors share the same thread pool, otherwise they will each have their own. Seems like a good idea to me. Thoughts?
Ole
29 Aug 07 at 6:25 pm
[...] on a 1.5+ JVM, add the following to your JAVA_OPTS in catalina.sh (or catalina.bat for Windows):PLAIN TEXT-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/j2ee/heapdumpsThen use a tool such as YourKit [...]
20 Tips for Using Tomcat in Production - Kappa’s fresh life
11 Sep 07 at 2:24 am
[...] Digital Sanctum » Blog Archive » 20 Tips for Using Tomcat in Production (tags: tomcat) [...]
Ian Joyce » Blog Archive » links for 2007-08-28
5 Jan 08 at 3:22 pm
Kind mail me the link to download Tomcat 6 Admin Console Application and hot to install it.
Thanks..
Albert
23 May 08 at 1:12 am
Thank you very much, great tips!
puzz
30 Oct 08 at 11:58 pm