Using supervisor
or monit
is the recommended, better way.
However, a quick-and-dirty hack that is working for me, is to use the pm2-save and pm2-resurrect utilities in combination with cron.
I ran pm2 save
to save a snapshot of all the node processes I wanted to keep running. Then, while logged in as the linux-user whom my pm2 and Node apps run as (e.g. ec2-user
on Amazon Linux in my case), I put this in my crontab (using crontab -e
):
* * * * * pm2 resurrect
This is telling the cron scheduler to run pm2 resurrect
every minute of every day. This ensures that even if the Linux kernel kills pm2 itself (which happens often when my tiny t2.micro
goes OOM), there will be at most 60 seconds of downtime: cron will ensure that pm2 and my NodeJS apps are resurrected (if necessary) automatically every minute.
pm2 resurrect
is really useful here, because it is idempotent in the sense that you can safely run it over and over again, and it won't restart any running processes or cause disruptions on reruns. It just checks if the required node apps are running, if they are, it doesn't do anything. However, if they are not already running, it uses the config recorded previously by pm2 save
to start these apps up.