Skip to content

PM2 cluster mode, watchdog, and respawn

Run Node.js services under PM2 with cluster scaling, automatic respawn, memory-threshold restarts, and the operational details that keep PM2 honest.

PM2 is the Node-specific process supervisor: it forks worker processes in cluster mode without the application using cluster directly, respawns crashes, restarts on memory thresholds, captures stdout/stderr to rotating files, and exposes a metrics endpoint. Used well, it is a thin shim over Node’s built-ins; used poorly it competes with systemd and produces zombie processes that nobody notices. This walks through the right way to configure PM2 in production and how to make it a peer to systemd, not a replacement.

How to verify

Confirm PM2 is supervising what you think it is:

pm2 list
pm2 show myapp
pm2 logs myapp --lines 50 --nostream
pm2 monit                                   # live CPU/mem dashboard
systemctl status pm2-deploy.service          # the systemd unit that owns pm2
ps -ef --forest | grep -E 'pm2|node' | head -20

If pm2 list shows your app but ps shows no node processes, the PM2 daemon thinks it’s alive but the workers are gone. Reboot the daemon: pm2 kill && pm2 resurrect.

What’s happening

PM2 starts a “God Daemon” — a long-running process that owns the workers. When you pm2 start app.js -i max, the daemon forks N node processes (using Node’s cluster internals) and supervises them. Crashes trigger respawn with exponential backoff. Memory above a threshold triggers a graceful restart. stdout/stderr are intercepted and piped to ~/.pm2/logs/ with rotation.

The daemon is itself a process and can crash. In production it must be supervised by something — systemd is the standard answer. pm2 startup generates a systemd unit that auto-resurrects PM2 on boot. Without that step, a server reboot leaves the daemon dead and your services with it.

The procedure

  1. Install PM2 globally (or per-project; both work, global is more common):

    sudo npm install -g pm2
    pm2 --version
  2. Define an ecosystem file — declarative configuration that pins everything explicitly. JSON is fine but .js lets you reference env vars:

    // ecosystem.config.cjs
    module.exports = {
      apps: [{
        name: 'myapp',
        script: './dist/main.js',
        instances: 'max',              // one per CPU
        exec_mode: 'cluster',
        max_memory_restart: '700M',    // restart any worker over 700 MiB
        node_args: '--max-old-space-size=512 --enable-source-maps',
        env_production: {
          NODE_ENV: 'production',
          PORT: '3000',
        },
        error_file: '/var/log/myapp/err.log',
        out_file:   '/var/log/myapp/out.log',
        log_date_format: 'YYYY-MM-DDTHH:mm:ss.SSS',
        wait_ready: true,              // wait for process.send('ready')
        listen_timeout: 10_000,
        kill_timeout: 30_000,          // SIGTERM grace before SIGKILL
      }],
    };
  3. The app must signal ready and respond to SIGTERM gracefully:

    const server = app.listen(3000, () => {
      if (process.send) process.send('ready');  // tell PM2 we're listening
    });
    process.on('SIGTERM', () => {
      server.close(() => process.exit(0));
      setTimeout(() => process.exit(1), 25_000).unref();
    });
  4. Start under PM2 and verify:

    pm2 start ecosystem.config.cjs --env production
    pm2 save                                # persist process list
    pm2 list
  5. Wire PM2 into systemd so reboots resurrect it. Run pm2 startup once as the deploy user:

    sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u deploy --hp /home/deploy
    sudo systemctl enable pm2-deploy
    sudo systemctl start pm2-deploy
  6. Add log rotation. PM2 has a built-in module, install once:

    pm2 install pm2-logrotate
    pm2 set pm2-logrotate:max_size 100M
    pm2 set pm2-logrotate:retain 14
    pm2 set pm2-logrotate:compress true
    pm2 set pm2-logrotate:rotateInterval '0 0 * * *'
  7. For zero-downtime deploys, pm2 reload does a one-at-a-time restart of workers. With wait_ready, PM2 waits for the new worker to send ‘ready’ before killing the old one — which is what makes the deploy actually zero-downtime:

    pm2 reload myapp

Common pitfalls

  • PM2 vs systemd is not either/or. PM2 supervises the workers, systemd supervises PM2. Skip the systemd step and a reboot kills everything.
  • pm2 stop does not free the worker assignments; the daemon remembers. After a stop, pm2 list still shows the process. Use pm2 delete to actually remove.
  • max_memory_restart triggers a hard kill if a worker’s RSS exceeds the threshold. If the worker is mid-request, the response is dropped. Pair it with a small graceful shutdown handler and a sensible threshold; don’t put it at 200 MiB on an app that uses 180 MiB normally.
  • pm2 logs reads from PM2’s daemon, which queues lines. Under high log volume, lines are dropped — visible only as gaps in timestamps. For high-throughput services, log to stdout, let systemd-journald capture, and don’t rely on PM2’s log capture.
  • instances: 'max' on a 64-core box spawns 64 workers — each with a separate heap. That can be too many; many workloads do better with instances: cpus / 2 and CPU work pushed to worker threads.

For the cluster pattern without PM2, see Node.js cluster mode with sticky load balancing. In the engagements Stack Harbor runs, PM2 is used when the team is comfortable with it and the operational benefits (zero-downtime reload, memory-threshold restart) justify the extra daemon; otherwise a systemd unit calling node dist/main.js directly is simpler. Either way, the supervision strategy is part of managed operations — not left to the dev to figure out on first boot.