Deploying Node.js Apps with PM2
PM2 keeps your Node apps running. Process management, clustering, and monitoring.
What is PM2?
PM2 is a production process manager for Node.js. It:
- Keeps your app running (auto-restart on crash)
- Load balances across CPU cores
- Provides monitoring and logs
- Handles deployments
Installation
npm install -g pm2
Basic Usage
# Start an app
pm2 start app.js
# With a name
pm2 start app.js --name "my-api"
# View running processes
pm2 list
# Monitor
pm2 monit
# Logs
pm2 logs
pm2 logs my-api
# Stop/restart
pm2 stop my-api
pm2 restart my-api
pm2 delete my-api
Ecosystem File
For production, use a config file:
// ecosystem.config.js
module.exports = {
apps: [{
name: 'api',
script: './dist/index.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000
},
env_development: {
NODE_ENV: 'development',
PORT: 3001
}
}]
};
# Start with ecosystem file
pm2 start ecosystem.config.js
# Start with development env
pm2 start ecosystem.config.js --env development
Cluster Mode
Spread load across all CPU cores:
{
instances: 'max', // Use all CPUs
exec_mode: 'cluster' // Enable cluster mode
}
PM2 handles load balancing automatically.
Auto-Restart on Server Boot
# Generate startup script
pm2 startup
# Save current process list
pm2 save
Now PM2 starts automatically when the server reboots.
Zero-Downtime Reload
pm2 reload my-api
In cluster mode, this restarts workers one at a time. Users never see downtime.
Monitoring
# Terminal dashboard
pm2 monit
# Or use PM2.io (free tier available)
pm2 link <public_key> <secret_key>
My Workflow
1. Build app locally 2. Push to server 3. `pm2 reload ecosystem.config.js` 4. Check `pm2 logs` for any issues
Simple, reliable, battle-tested.
When to Use Something Else
- **Docker** - If you're containerizing everything
- **Kubernetes** - At scale with orchestration needs
- **Serverless** - For event-driven functions
PM2 is perfect for traditional VPS deployments. If you're running on a DigitalOcean droplet or similar, it's the right tool.