Adiii
Adiii

Reputation: 60164

pm2 --max-restarts limit not working and continuous restarting crash host system

I tried pm2 to restrict restart limit with --max-restarts but it's not working and also tired min_uptime

sudo pm2 start server.js --max-restarts=5 

And I also tried with yml file

apps:
  - name: node-mt
    script: server-socket.js
    watch: true
    max_restarts: 5
    min_uptime: 5000

But it's not limiting restart of the application.

If pm2 crashes regularly it crashed the host system and memory usage reached from 300mb to 800mb.

Its normal state when app running.

enter image description here

When an application crashes. Then graph goes very high.

I need to stop max restart to avoid crashing host due to high usage of memory. I don't want to restrict memory usage flag. enter image description here

Upvotes: 19

Views: 8672

Answers (1)

Ridham Tarpara
Ridham Tarpara

Reputation: 6170

PM2 max_restarts ane min_uptime works perfectly fine. You need to understand the analogy of both.

As per documentation

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

This means that if your min_uptime is 5000 and max_restarts is 5 then your app will be considered errored if the app is crashed and restarted 5 time in less than 5000ms. If it restarts 4 times in 5 second than it will not consider it as errored and continue restarting it.

If your app keeps restarting with this config that means your app is not restarting 5 times in 5 second. The possible solution is give a relatively high number in min_uptime like an hour or so for your case or you can find it by manual test.

I have a good time understanding this when I first encountered it with my node cron app and created following demo.

app.js

setTimeout(function () {
  console.log('killed');
  process.exit(1)
}, 100);

ecosystem.config.json

{
  "apps" : [{
    "name"         : "api",
    "script"       : "./app.js",
    "max_restarts" : 3,
    "min_uptime"   : 300
  }]
}

This will kill your process but if you change the timeout to 130+(I don't know why but it works for the values less than 130 as may be ms pricision and not considering config till 1st restart) then it won't work. It will start restarting the app.

PM2 documnetation

P.S.

min_uptime can be given in string too.

enter image description here

Upvotes: 18

Related Questions