Process management, clustering, logs & deployment for Node.js
DevOps# Install
npm install -g pm2
# Start app
pm2 start app.js
pm2 start app.js --name my-app
pm2 start app.js -i max # cluster mode (all CPUs)
pm2 start npm -- start # npm script
pm2 start python -- script.py # python script
# Quick status
pm2 list # list all processes
pm2 status # same as list
pm2 show <id|name> # detailed infopm2 stop <id|name|all>
pm2 restart <id|name|all>
pm2 reload <id|name|all> # zero-downtime reload
pm2 delete <id|name|all>
# Start with options
pm2 start app.js --watch # auto-restart on change
pm2 start app.js --max-memory-restart 200M
pm2 start app.js --cron "0 */1 * * *"
# Startup on boot
pm2 startup # generate startup script
pm2 save # save current list
pm2 unstartup # remove startuppm2 logs # all logs
pm2 logs <name> # specific app
pm2 logs --lines 200 # last 200 lines
pm2 logs --json # JSON format
pm2 flush # clear all logs
# Log rotation
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7# Start in cluster mode
pm2 start app.js -i max # use all CPUs
pm2 start app.js -i 4 # 4 instances
# Scale
pm2 scale app +2 # add 2 instances
pm2 scale app 6 # set to 6 total
# Graceful reload (zero downtime)
pm2 reload app # rolling restart# Generate: pm2 ecosystem
// ecosystem.config.js
module.exports = {
apps: [{
name: "my-app",
script: "app.js",
instances: "max",
exec_mode: "cluster",
watch: true,
env: {
NODE_ENV: "development",
PORT: 3000
},
env_production: {
NODE_ENV: "production",
PORT: 8080
}
}]
};
# Start with ecosystem
pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env productionpm2 monit # terminal dashboard
# PM2 Plus (web dashboard)
pm2 plus # connect to pm2.io
# Process info
pm2 show <name>
pm2 describe <name>
pm2 prettylist # formatted JSON
pm2 jlist # raw JSON// In ecosystem.config.js
module.exports = {
deploy: {
production: {
user: "deploy",
host: "server.com",
ref: "origin/main",
repo: "git@github.com:user/repo.git",
path: "/var/www/app",
"post-deploy": "npm install && pm2 reload ecosystem.config.js"
}
}
};
# First time
pm2 deploy production setup
# Deploy
pm2 deploy production