How to automatically restart Apache Tomcat when it dies in Debian server

Wednesday January 04, 2012 ()

This short blog is about monitoring and restarting Tomcat through crontab if and when it silently dies for whatever cause. The process described here works and was tested in our Tomcat 7 installation in Debian Squeeze servers.

Below is the entire script.

#!/bin/sh

/bin/netstat -ln | /bin/grep ":8080 " | /usr/bin/wc -l | \
     /usr/bin/awk '{if ($1 == 0) system("/etc/init.d/tomcat start") }'

Let us breakdown the commands of our script above.

/bin/netstat -ln

netstat is a program to list network connections. The option -l tells netstat to print only listening sockets. -n commands netstat to list addresses and ports and not to resolve hosts.

/bin/grep ":8080 "

grep searches lines of input for match against a pattern from an input file or standard input. In our case, it searches for a match for ":8080 " from the output of netstat taken from standard input. Our Tomcat process listens to port 8080. If you used other port for your Tomcat installation, you may want to change this to match the port you are using.

/usr/bin/wc -l

wc counts the number of lines from an input. In our case, the output from grep. This is accomplished with the -l option.

/usr/bin/awk '{if ($1 == 0) system("/etc/init.d/tomcat start") }'

And finally we create simple awk program to start Tomcat if wc passes 0 to it, which is 0 number of lines counted by wc from its input.

Save the script giving it any desired name and to desired location. For the sake of this blog, we name our script tomcat-start and put it in /opt/scripts. Change the access permission to the newly saved file to include execute attribute.

chmod +x tomcat-start

To learn more about the command above, please visit the documentation of each command or visit its man pages.

Crontab

Our script is done. Now we ask crontab to run it at a defined interval. Here crontab checks our Tomcat process every 5 minutes.

Run crontab -e to open the crontab editor and then enter the line below and save.

*/5 * * * * /opt/scripts/tomcat-start /dev/null  \
     >> /opt/scripts/tomcat-start-log.txt

Our crontab entry above says run tomcat-start every 5 minutes as already mentioned and save the screen output of Tomcat to to our log file, tomcat-start-log.txt. You may want to change the 5-minute interval to suit your needs.

That's it. Good luck.


4,096

Comments (How to automatically restart Apache Tomcat when it dies in Debian server )