Node.js PM2

PM2 is a process manager for Node.js. It keeps your app running, restarts it after a crash, and spreads work across all CPU cores. A plain node app.js command stops when the terminal closes or an error occurs. PM2 solves both problems.

The Security Guard Shift Idea

A building needs a guard at the door all day. When one guard falls sick, a manager sends a replacement right away. PM2 plays the manager for your app. A crashed process gets replaced within moments.

 Without PM2:   app crashes --> site is down until you notice

 With PM2:      app crashes --> PM2 restarts it --> site stays up

What PM2 Offers

  • Automatic restart after crashes.
  • Start on server boot.
  • Cluster mode across CPU cores.
  • Log collection and viewing.
  • Live monitoring of memory and CPU.
  • Zero-downtime reloads during updates.

Install PM2

npm install -g pm2

Start an App

pm2 start index.js --name shop-api

PM2 runs the app in the background. Close the terminal and the app keeps running.

Daily Commands

pm2 list                  // show all apps
pm2 logs shop-api         // read live logs
pm2 monit                 // open the live monitor
pm2 restart shop-api      // restart the app
pm2 reload shop-api       // restart with no downtime
pm2 stop shop-api         // stop the app
pm2 delete shop-api       // remove it from PM2

The Status Table

+----+------------+--------+------+--------+---------+
| id | name       | mode   | pid  | status | memory  |
+----+------------+--------+------+--------+---------+
| 0  | shop-api   | fork   | 4112 | online | 48 MB   |
+----+------------+--------+------+--------+---------+

The status column shows online, stopped, or errored.

Use Cluster Mode

One Node.js process uses one CPU core. Cluster mode starts a copy for each core and shares requests between them.

pm2 start index.js -i max --name shop-api
              +--> Copy 1 (core 1)
Visitors --> PM2 --> Copy 2 (core 2)
              +--> Copy 3 (core 3)
              +--> Copy 4 (core 4)

The option -i max uses every core. Pick a number such as -i 2 for a fixed count. Keep the app stateless in cluster mode. Store sessions in Redis or a database, not in process memory.

Use an Ecosystem File

A configuration file stores your settings. Create it with pm2 init simple.

// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: "shop-api",
      script: "./index.js",
      instances: "max",
      exec_mode: "cluster",
      max_memory_restart: "300M",
      env: {
        NODE_ENV: "development",
        PORT: 3000
      },
      env_production: {
        NODE_ENV: "production",
        PORT: 8080
      }
    }
  ]
};
pm2 start ecosystem.config.js --env production

The setting max_memory_restart restarts a process that uses too much memory. This setting protects against slow memory leaks.

Start on Server Boot

A server restart stops all processes. Two commands bring PM2 back automatically.

pm2 startup          // prints a command; run that command
pm2 save             // saves the current app list
Server boots --> PM2 starts --> PM2 loads saved list --> apps run

Manage Logs

PM2 writes logs to the ~/.pm2/logs folder.

pm2 logs                 // all apps
pm2 logs shop-api --lines 50
pm2 flush                // clear logs

Install the rotation module so files stay small.

pm2 install pm2-logrotate

Update Without Downtime

The reload command restarts cluster copies one at a time. Visitors keep getting answers during the update.

git pull
npm ci --omit=dev
pm2 reload shop-api

PM2 and Docker

Docker already restarts failed containers, and orchestration tools handle scaling. Use PM2 directly on virtual servers. Container setups often skip it.

Good Habits

  • Name every app clearly.
  • Run pm2 save after any change to the app list.
  • Set a memory restart limit.
  • Keep configuration in an ecosystem file under version control.

Practice Tasks

  • Start a sample server with PM2, then kill its process and watch PM2 restart it.
  • Run the same app in cluster mode with two instances.
  • Write an ecosystem file with separate development and production settings.