:: node.js - keep alive with bash script and cron ::
For whatever reason I cannot get monit to keep node alive on a ubuntu lucid virtual machine. I've no problem getting monit to carry out the same task on CentOS virtual machines.
So I wrote a little bash script to keep node alive and run it every minute with cron.
#!/bin/bash
PIDFILE=/home/node/app/pids/node.pid
NODE=/home/node/local/node/bin/node
APP=/home/node/app/app.js
echo 'Checking if node is active'
if [ -f $PIDFILE ] ; then
if [ -d "/proc/`cat $PIDFILE`" ]; then
echo "Script is running"
else
echo "Script is not running - attempting to Start"
rm -f $PIDFILE
$NODE $APP & echo $! > $PIDFILE&
fi else
echo "Script is not running - attempting to Start"
rm -f $PIDFILE
$NODE $APP & echo $! > $PIDFILE&
fi
(The script was inspired by Stephen, http://stephen.rees-carter.net/2011/05/simple-bash-keep-alive-script/)
A little gotcha I encountered was that node couldn't load modules and bombed out as a result. I guess cron reads in your bashrc and as I had put path stuff for node in .profile modules couldn't be located. The following changes to the crontab file fixed these problems.
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/home/node/local/node/bin
NODE_PATH=/home/node/local/node:/home/node/local/node/lib/node_modules
HOME=/home/node
# m h dom mon dow command
*/1 * * * * /home/node/scripts/keep-node-alive.sh
All is working well now. The final stage would be to turn off cron messages so you don't end up with a million messages telling you "Script is running".