There are many web hosting services that provide ways to monitor your running server and restart it when necessary. But not all of them do, and if you’re stuck like I was on a shared server with no such fancy pants watcher, you may find this simple method using common tools useful.
The watcher script simply runs one time and checks if a server process is running, and if it isn’t, starts it.
In my case, I needed to manually set my $PATH variable, otherwise the cron job wouldn’t be able to run node:
set PATH so cron job can find and execute 'node'
The next part of the script uses the
ps aux command to see if my server processes are running. If all are running, the script exits early.
In my case, I am looking for two processes:
This one liner bears some explanation:
(ps aux|grep "index.js"|grep -v "grep"|wc -l)
It evaluates to 1 if “index.js” is running, 0 if it’s not. (the
grep -v "grep" bit is needed, because the prior
grep "index.js" often shows up as a process in
The remainder of the script simply restarts my server processes:
using pm2, delete then restart my server processes
crontab -e to add a cron job single line that will run my script every minute, logging
With just a simple script and one cron job line, I now have a watcher that restarts my web services whenever necessary. Which is pretty important, because the shared server I’m using reboots often, but it doesn’t restart my services.