How do I limit the number of auto-restarts on 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.

Upvotes: 18

Views: 11245

Answers (3)

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27525

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:

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

Upvotes: 3

Krishan Kant Sharma
Krishan Kant Sharma

Reputation: 361

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

Upvotes: 5

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7267

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

Upvotes: 14

Related Questions