How to monitor tomcat application and restart if not running?
I have a web application running on Tomcat and would like to have an automated way of monitoring the application to ensure it is running, and if not start/restart tomcat (and also send an email alert). I'd like to do more than just check that Tomcat is running and ensure that a default page from the application can be loaded.
Is there any tool that would be best to do this, aside from writing a shell script and running it as a cron job?
Solution 1:
Please look into the Monit utility.
This is a daemon and process-watching tool and can provide the alerts and defined actions that you may need.
A quick example:
check process tomcat with pidfile "/var/run/tomcat/tomcat.pid"
start program = "/usr/local/tomcat/bin/startup.sh" as uid tomcat gid tomcat
stop program = "/usr/local/tomcat/bin/shutdown.sh" as uid tomcat gid tomcat
if failed port 8080 then alert
if failed port 8080 for 5 cycles then restart
Solution 2:
This might help someone!!
If one do not want to use any monitoring tool, then set up an email configurtion in Ubuntu server using mailutils package.
https://rianjs.net/2013/08/send-email-from-linux-server-using-gmail-and-ubuntu-two-factor-authentication
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-14-04
To monitor Tomcat status you can use below script and set up cron job which runs every minute/hour/day according to your needs.
#!/bin/bash
TOMCAT_HOME=/opt/tomcat
PUBLIC_IP=`wget http://ipecho.net/plain -O - -q ; echo`
EMAIL_BODY="Hi Admin,\n\n$PUBLIC_IP Tomcat is down at $(date -d "+330 minutes" +"%Y-%m-%d %T") IST, Please take necessary action.\n\n\nDo not reply to this email as it is auto generated by Ubuntu system\n"
tomcat_pid() {
echo `ps aux | grep org.apache.catalina.startup.Bootstrap | grep -v grep | awk '{ print $2 }'`
}
start() {
pid=$(tomcat_pid)
if [ -n "$pid" ]
then
echo "Tomcat is already running (pid: $pid)"
else
# Start tomcat
echo "Starting tomcat"
/bin/sh $TOMCAT_HOME/bin/startup.sh
fi
return 0
}
pid=$(tomcat_pid)
if [ -n "$pid" ]
then
echo "Tomcat is running with pid: $pid"
#stop
else
echo "Tomcat is not running"
# send an email alert then start
echo -e $EMAIL_BODY | mail -s "$PUBLIC_IP Tomcat is down" [email protected]
echo "Mail sent"
#remove cache and release memory occupied by heavy processes
start
fi
exit 0