Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit the number of auto-restarts on pm2?

Tags:

node.js

pm2

I have a node server running on pm2 which depends on some external services.

When those servers go down I pm2 starts restarting my app, but this will keep going until it clogs up my cpu and ram on the server, restarting as much as 50 times a minute.

Is there a way to limit the numbers of restarts on pm2? There is a way to restart the server when the server reaches a certain RAM memory level, so I would hope this feature I am asking for exists.

like image 714
Bryan Arbelo - MaG3Stican Avatar asked Jan 16 '17 02:01

Bryan Arbelo - MaG3Stican


3 Answers

You can use combination of max_restarts and min_uptime to restrict the app to restart consecutively.

number of consecutive unstable restarts (less than 1sec interval or custom time via min_uptime) before your app is considered errored and stop being restarted

More information about max_restarts and min_uptime is available here

like image 149
Tuan Anh Tran Avatar answered Nov 14 '22 07:11

Tuan Anh Tran


Use PM2 ecosystem.config.js file like this:

module.exports = {
  apps : [{
    name: "app",
    script: "./app.js",
    merge_logs: true,
    max_restarts": 50, //Here you can define your max restarts
    instances: "max",
    max_memory_restart: "200M",
    env: {
      NODE_ENV: "development",
    },
    env_production: {
      NODE_ENV: "production",
    }
  }]
}

Start your server by following command:

pm2 start ecosystem.config.js //uses variables from `env`
pm2 start ecosystem.config.js --env production //uses variables from `env_production`

For more details see below link:

PM2 Runtime | Guide | Ecosystem File

like image 3
Krishan Kant Sharma Avatar answered Nov 14 '22 09:11

Krishan Kant Sharma


Options for config file if you have: ecosystem.config.js

{
    watch_delay: 5000,

    exp_backoff_restart_delay: 100,

    restart_delay: 1000,
    max_restarts: 2,
    min_uptime: 5000,
    autorestart: false,
}

Otherwise, give the same command line, as below:

pm2 start app.js --restart-delay=3000
pm2 start app.js --no-autorestart

They themselves know the issue, so see the 1st link below:

  • https://pm2.keymetrics.io/docs/usage/restart-strategies/
  • https://pm2.keymetrics.io/docs/usage/process-management/

Mine got fixed only after watch_delay: 5000, and nothing else was required.

like image 2
Manohar Reddy Poreddy Avatar answered Nov 14 '22 08:11

Manohar Reddy Poreddy