occasionally crashes if you do frequent hot-deploys or if you are running it on a machine with low memory. Every time crashes someone has to manually restart it, so I wrote a script which automatically detects that has crashed and restarts it.

Here’s the pseudo logic:

every few minutes {
  check tomcat status;

  if (status is "not running") {
    start tomcat;

Here’s a shell script to implement the above logic. It assumes that you are running on a / system and have /etc/init.d/tomcat* script to manage tomcat.

Adjust the path to “/etc/init.d/tomcat” in the script below to reflect the correct path on your computer. Sometimes it is called /etc/init.d/tomcat5 or /etc/init.d/tomcat6 depending on your tomcat version. Also make sure that the message “Tomcat Servlet Container is not running.” matches with the message that you get when you run the script when tomcat is stopped.

#! /bin/sh
STOPPED_MESSAGE="Tomcat Servlet Container is not running."

if [ "`$SERVICE status`" == "$STOPPED_MESSAGE"];
  $SERVICE start

To run the script every 10 minutes:

1. Save the above script to “//bin/recover-tomcat.sh”.

2. Add execute permission:

chmod +x /root/bin/recover-tomcat.sh

3. Add this to root’s , type the following as root:

crontab -e

4. Add the following lines to the crontab:

#  tomcat every 10 minutes  
 */10 * * * * /root/bin/recover-tomcat.sh

What if I don’t have /etc/init.d/tomcat* script on my computer?

Tomcat creates a pid , typically in the TOMCAT_HOME/bin directory. This contains the process id of the tomcat process running on the machine. The pseudo logic in that case would be:

 if (the PID file does not exist) {  
   // conclude that tomcat is not running  
   start tomcat  
 else {  
   read the process id from the PID file  
   if (no process that id is running) {  
     // conclude that tomcat has crashed  
     start tomcat  

You can implement the above logic as follows. The following is experimental and is merely a suggested way, test it on your computer before using it.

# adjust this to reflect tomcat home on your computer

if [ -f $TOMCAT_HOME/bin/tomcat.pid ]
  echo "PID file exists"
  pid="`cat $TOMCAT_HOME/bin/tomcat.pid`"
  if [ "X`ps -p $pid |  '{print $1}' | tail -1`" = "X"]
    echo "Tomcat is running"
    echo "Tomcat had crashed"
  echo "PID file does not exist. Restarting..."

Why would tomcat crash?

The most common reason is low memory. For example, if you have allocated 1024MB of max memory to tomcat and enough memory is not available on that machine. Other reasons may involve repeated hot-deploys causing memory leaks, rare JVM bugs causing the JVM to crash.

Print Friendly, PDF & Email



Bài viết liên quan