Linux环境下Tomcat 9配置-XX:+HeapDumpOnOutOfMemoryError参数及setenv.sh文件缺失问题
Let's work through your problem step by step—first getting the heap dump configuration working, then answering your questions about missing files and existing VM parameters.
1. Why You Don't See setenv.sh in /usr/share/tomcat9
When you install Tomcat via a package manager (like apt on Debian/Ubuntu), the default setup doesn't include a setenv.sh file. This file is meant for user-defined customizations (like VM flags), so you have to create it yourself. Also, note that for package-managed Tomcat:
CATALINA_HOMEis/usr/share/tomcat9(this holds core Tomcat binaries/libraries)- Configuration files live in
/etc/tomcat9(linked toCATALINA_HOME/confas you saw) - Application-specific data (webapps, logs, work directories) is in
/var/lib/tomcat9(this is yourCATALINA_BASE)
2. Create setenv.sh in the Correct Location
You need to create setenv.sh in /etc/tomcat9—Tomcat's startup scripts are configured to automatically load this file. Here's how:
- Switch to the config directory:
cd /etc/tomcat9 - Create the file with a text editor (nano is usually available):
sudo nano setenv.sh - Add these lines (we'll specify a dump path to make it easy to find later):
# Enable heap dump on OutOfMemoryError CATALINA_OPTS="${CATALINA_OPTS} -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/lib/tomcat9/logs/heapdump.hprof"Note: Don't wrap the
-XXflag in-Dparam=—that's for system properties, not JVM flags. Just add it directly toCATALINA_OPTS. - Save and exit nano (press
Ctrl+O, hit Enter, thenCtrl+X). - Give the file execute permissions so Tomcat can run it:
sudo chmod +x setenv.sh
3. Where to Find Existing VM Parameters
Your pre-configured VM flags might be stored in one of these locations (common for Debian/Ubuntu Tomcat):
/etc/tomcat9/tomcat9.conf: Check forJAVA_OPTSorCATALINA_OPTSentries here./etc/default/tomcat9: This file often holds default JVM settings for Tomcat./lib/systemd/system/tomcat9.service: If you're using systemd, look forEnvironmentlines that define JVM flags.
To quickly check these, use grep:
# Check tomcat9.conf grep -E "(JAVA_OPTS|CATALINA_OPTS)" /etc/tomcat9/tomcat9.conf # Check /etc/default/tomcat9 grep -E "(JAVA_OPTS|CATALINA_OPTS)" /etc/default/tomcat9 # Check systemd service file grep -E "Environment" /lib/systemd/system/tomcat9.service
4. Restart Tomcat and Verify the Setup
- Restart Tomcat (use whichever command fits your server):
# For systemd sudo systemctl restart tomcat9 # For init.d sudo /etc/init.d/tomcat9 restart - Verify the flag is active by checking Tomcat's process arguments:
ps aux | grep tomcat9 | grep -E "(HeapDumpOnOutOfMemoryError|HeapDumpPath)"
If you see the flags in the output, you're good to go! Next time your app hits an OutOfMemoryError, a heap dump will be generated at /var/lib/tomcat9/logs/heapdump.hprof for analysis with Eclipse MAT.
内容的提问来源于stack exchange,提问作者willberthos




