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

3

18

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.

Evening answered 16/1, 2017 at 2:44 Comment(1)
"restart the server when the server reaches a certain RAM memory level" this would be a very very bad way to deal with memory leaks... Not sure why you want to do this.Notum
V
13

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

Viyella answered 16/1, 2017 at 3:33 Comment(0)
S
5

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

Suppositive answered 6/12, 2018 at 9:18 Comment(0)
P
3

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.

Pesticide answered 21/2, 2021 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.