Skip to main content
Practice Problems

What is PM2 and how to manage Node.js processes in production?

Process Management in Node.js

In production, you need to ensure your Node.js application:

  • Stays running if it crashes (auto-restart)
  • Utilizes all CPU cores (cluster mode)
  • Can be monitored (logs, metrics)
  • Can be deployed without downtime (zero-downtime reload)

PM2 is the most popular production process manager for Node.js.


Why Not Just node server.js?

ProblemWithout PM2With PM2
App crashesProcess dies, stays deadAuto-restarts
Multi-coreUses 1 core onlyCluster mode (all cores)
LoggingGoes to stdout, lostPersisted log files
DeployDowntime during restartZero-downtime reload
MonitoringNone built-inCPU, memory, restarts

Getting Started with PM2

bash
# Install globally npm install -g pm2 # Start application pm2 start server.js # Start with options pm2 start server.js --name "my-api" -i max # cluster mode, all CPUs # List running processes pm2 list # Monitor in real-time pm2 monit # View logs pm2 logs pm2 logs my-api --lines 100

Ecosystem File (ecosystem.config.js)

js
module.exports = { apps: [{ name: 'my-api', script: 'dist/main.js', instances: 'max', // Use all CPU cores exec_mode: 'cluster', // Cluster mode max_memory_restart: '1G', env: { NODE_ENV: 'production', PORT: 3000 }, env_staging: { NODE_ENV: 'staging', PORT: 3001 } }] };
bash
# Start with ecosystem file pm2 start ecosystem.config.js # Start for specific env pm2 start ecosystem.config.js --env staging

Key PM2 Commands

CommandDescription
pm2 start app.jsStart
pm2 stop appStop
pm2 restart appRestart
pm2 reload appZero-downtime reload
pm2 delete appRemove from PM2
pm2 listList all processes
pm2 monitReal-time dashboard
pm2 logsView logs
pm2 saveSave process list
pm2 startupAuto-start on boot

Cluster Mode

PM2 cluster mode spawns multiple instances of your app, distributing load across CPU cores:

bash
# Start 4 instances pm2 start server.js -i 4 # Start on all available CPUs pm2 start server.js -i max # Scale up/down pm2 scale my-api +2 # Add 2 more instances pm2 scale my-api 2 # Set to exactly 2

Zero-Downtime Deployment

bash
# Reload gracefully (one by one in cluster mode) pm2 reload my-api # Deployment workflow pm2 deploy ecosystem.config.js production setup pm2 deploy ecosystem.config.js production

Alternatives to PM2

ToolUse Case
DockerContainer-based deployment
systemdLinux service management
KubernetesContainer orchestration at scale
nodemonDevelopment only (not production)
foreverSimple process manager (legacy)

Production recommendation: Use PM2 for simple deployments on VPS. For microservices at scale, consider Docker + Kubernetes with proper health checks and auto-scaling.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems