How to use PM2 for process management

· Category: Node.js

Short answer

PM2 is a production process manager for Node.js that handles clustering, zero-downtime deployments, logging, and automatic restarts.

Steps

  1. Install PM2 globally: npm install -g pm2.
  2. Start your app: pm2 start app.js --name my-app.
  3. Enable cluster mode: pm2 start app.js -i max.
  4. Monitor processes: pm2 monit or pm2 status.
  5. Save and configure startup scripts with pm2 startup and pm2 save.

Tips

  • Use an ecosystem file (ecosystem.config.js) to define environment variables, instances, and restart policies.
  • PM2 logs can be aggregated and rotated automatically.

Common issues

  • Without pm2 save, processes will not restart after a system reboot.
  • Cluster mode requires stateless apps because workers do not share in-memory data.