Piotr Leniartek
Piotr Leniartek

Reputation: 1187

Restart node.js after crash in pm2

According to this question, pm2 should restart crashed applications.

When my application crashes nothing happens and the process is missing from pm2 list. Do I have to somehow activate an 'auto restart option'?

I am using:

Upvotes: 1

Views: 8064

Answers (2)

codemacabre
codemacabre

Reputation: 1122

PM2 should automatically restart apps, but there are a few alternative ways to ensure PM2 will do this (including the --watch command you've already linked to). The route I've taken is:

$ pm2 startup systemd

PM2 will then output instructions to execute the following command (note, I'd recommend copy/pasting the output from the above startup command rather than using my example below):

$ sudo su -c "env PATH=$PATH:/usr/bin pm2 startup systemd -u USERNAME --hp /home/USERNAME"

This will create the environment variables to restart your processes if the app crashes or the server reboots.

Upvotes: 0

Joe
Joe

Reputation: 2430

I've had poor results trying to use PM2 as the sole means by which to monitor my Node.js applications. In the end the approach I took was to use to Monit to monitor the application process and use pm2 within the monit configuration script to startOrRestart or stop the process. For example, in a monitrc file:

check process node_app matching /home/webapps/node_app/app.js start program = "/bin/bash -lc 'cd /home/webapps/node_app && PM2_HOME=/home/webapps/.pm2 /usr/bin/pm2 startOrRestart processes.json'" stop program = "/bin/bash -lc 'cd /home/webapps/node_app && PM2_HOME=/home/webapps/.pm2 /usr/bin/pm2 stop processes.json'"

Not only does this allow you to "watch the watcher" it helps as a work-around for the persistent PM2 fails to restart applications after a reboot bug.

Upvotes: 2

Related Questions