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?
| Problem | Without PM2 | With PM2 |
|---|---|---|
| App crashes | Process dies, stays dead | Auto-restarts |
| Multi-core | Uses 1 core only | Cluster mode (all cores) |
| Logging | Goes to stdout, lost | Persisted log files |
| Deploy | Downtime during restart | Zero-downtime reload |
| Monitoring | None built-in | CPU, 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 100Ecosystem 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 stagingKey PM2 Commands
| Command | Description |
|---|---|
pm2 start app.js | Start |
pm2 stop app | Stop |
pm2 restart app | Restart |
pm2 reload app | Zero-downtime reload |
pm2 delete app | Remove from PM2 |
pm2 list | List all processes |
pm2 monit | Real-time dashboard |
pm2 logs | View logs |
pm2 save | Save process list |
pm2 startup | Auto-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 2Zero-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 productionAlternatives to PM2
| Tool | Use Case |
|---|---|
| Docker | Container-based deployment |
| systemd | Linux service management |
| Kubernetes | Container orchestration at scale |
| nodemon | Development only (not production) |
| forever | Simple 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.