What Is PM2?
PM2 is a production process manager for Node.js applications. It keeps your app running, handles restarts on failure, provides logging, and supports clustering for multi-core utilization.
Installation
npm install -g pm2Basic Usage
# Start an application
pm2 start app.js --name "my-api"
# Start with environment variables
pm2 start app.js --name "my-api" --env production
# View running processes
pm2 list
# Monitor in real-time
pm2 monitCluster Mode
Run multiple instances across CPU cores:
# Use all available cores
pm2 start app.js -i max --name "my-api"
# Use specific number of instances
pm2 start app.js -i 4 --name "my-api"Ecosystem File
Create ecosystem.config.js:
module.exports = {
apps: [{
name: "my-api",
script: "app.js",
instances: "max",
exec_mode: "cluster",
env: {
NODE_ENV: "production",
PORT: 3000
},
max_memory_restart: "500M",
log_date_format: "YYYY-MM-DD HH:mm:ss",
error_file: "./logs/error.log",
out_file: "./logs/output.log"
}]
};
pm2 start ecosystem.config.jsAuto-Start on Boot
pm2 startup systemd
# Run the generated command
pm2 saveCommon Commands
pm2 restart my-api # Restart
pm2 reload my-api # Zero-downtime reload
pm2 stop my-api # Stop
pm2 delete my-api # Remove from PM2
pm2 logs my-api # View logs
pm2 logs --lines 100 # Last 100 lines