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.
Let us breakdown the commands of our script above.
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.
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.
wc counts the number of lines from an input. In our case, the output from grep. This is accomplished with the -l option.
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.
To learn more about the command above, please visit the documentation of each command or visit its man pages. CrontabOur 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.
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. |