← Back to Node.js, page 5

nodejs-0098 · Easy fresher

What does PM2 do for a Node.js app, and how do an ecosystem file, cluster mode and a graceful reload work?

PM2 is a process manager that starts Node apps, restarts them on a crash, keeps logs, and can run several copies in cluster mode. An ecosystem file describes the apps (script, instances, env, restart limits). pm2 reload restarts workers one by one for zero downtime, and the app can tell PM2 when it is ready with process.send('ready').

Full answer

A process manager keeps an app running after a crash, starts it on boot and gives basic monitoring. PM2 is the best-known one for Node. On container platforms the platform restarts crashed containers, so PM2 is mostly used on virtual machines and servers.

Common commands (not run on this box, PM2 is not installed here):

  • pm2 start ecosystem.config.js
  • pm2 list, pm2 logs, pm2 monit
  • pm2 restart app (stop and start), pm2 reload app (one by one, zero downtime in cluster mode)
  • pm2 save and pm2 startup: restart apps after a server reboot.

Ecosystem file (ecosystem.config.js) is a JavaScript module that exports { apps: [ ... ] }. Useful fields:

  • name, script, args, cwd.
  • instances: a number, or 'max' for one per CPU core. exec_mode: 'cluster' uses Node's cluster module so instances share the port.
  • env and env_production: environment variables, chosen with --env production.
  • max_memory_restart: restart a worker that grows past a limit ('300M'). A guard, not a fix for leaks.
  • autorestart, max_restarts, min_uptime: avoid endless crash loops.
  • wait_ready: true with listen_timeout: PM2 waits for process.send('ready') before it considers the app online and before it stops the old instance during a reload.
  • kill_timeout: how long PM2 waits after the stop signal (SIGINT by default) before it sends SIGKILL.
  • shutdown_with_message: use a message instead of a signal (useful on Windows).

Graceful reload recipe: the app starts its server, then calls process.send?.('ready'). On SIGINT it closes the server, finishes requests and exits, within kill_timeout. Then pm2 reload brings up new instances before the old ones leave.

Remember the cluster limits: no shared memory between instances, so keep state in an external store.

javascript
const { spawn } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

// 1. An ecosystem file is plain JavaScript. This is what you would save as ecosystem.config.js.
const ecosystem = {
  apps: [{
    name: 'schoolabe-api',
    script: './server.js',
    instances: 'max',
    exec_mode: 'cluster',
    wait_ready: true,
    listen_timeout: 10000,
    kill_timeout: 5000,
    max_memory_restart: '300M',
    env: { NODE_ENV: 'development', PORT: 3000 },
    env_production: { NODE_ENV: 'production', PORT: 8080 },
  }],
};
const app = ecosystem.apps[0];
console.log('app:', app.name, '| mode:', app.exec_mode, '| instances:', app.instances);
console.log('production env:', { ...app.env, ...app.env_production });

// 2. What PM2 expects from the app: tell "ready", and exit cleanly on SIGINT.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pm2-demo-'));
fs.writeFileSync(path.join(dir, 'server.js'), `
const http = require('node:http');
const server = http.createServer((req, res) => res.end('ok'));
server.listen(0, '127.0.0.1', () => {
  if (process.send) process.send('ready');          // PM2 sets up this channel when wait_ready is on
});
process.on('SIGINT', () => {
  server.close(() => { console.log('app: closed the server, exiting'); process.exit(0); });
});
`);

// The parent plays the role of PM2 for one reload step.
const child = spawn(process.execPath, [path.join(dir, 'server.js')], { stdio: ['ignore', 'pipe', 'inherit', 'ipc'] });
let output = '';
child.stdout.on('data', (chunk) => (output += chunk));
child.once('message', (message) => {
  console.log('pm2 (simulated): app said', JSON.stringify(message), '-> mark it online, now stop the old instance');
  child.kill('SIGINT'); // PM2 sends SIGINT to the old instance first
});
child.on('exit', (code) => {
  console.log(output.trim());
  console.log('exit code:', code);
  fs.rmSync(dir, { recursive: true });
});

PM2 itself is not installed here, so the parent script plays PM2's part for one step. The pm2 commands in the answer were not run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): app: schoolabe-api | mode: cluster | instances: max production env: { NODE_ENV: 'production', PORT: 8080 } pm2 (simulated): app said "ready" -> mark it online, now stop the old instance app: closed the server, exiting exit code: 0

Key points

  • PM2 restarts, scales and logs Node apps.
  • The ecosystem file describes apps, instances and env.
  • reload is zero downtime in cluster mode when the app signals ready.
  • Handle the stop signal (SIGINT by default) for a clean exit.

Common mistakes

  • Using restart instead of reload and dropping requests.
  • Running PM2 cluster mode and keeping sessions in memory.
  • Setting max_memory_restart and calling the leak solved.
  • Letting a crash loop run without min_uptime and max_restarts.

Follow-ups

  • How does PM2 cluster mode relate to the cluster module?
  • When would you not use PM2?
  • How does PM2 send logs and how do you rotate them?

Tips

  • Name restart versus reload.
  • Mention wait_ready and process.send('ready').
  • Say that containers often replace PM2.