4 min read
•Question 39 of 62mediumWhat is PM2 and how to use it?
Production process management with PM2.
What You'll Learn
- What PM2 is
- Key commands
- Configuration options
What is PM2?
PM2 is a production process manager for Node.js with load balancing, monitoring, and zero-downtime deployments.
Installation & Basic Commands
$ terminalBash
npm install -g pm2
# Start app
pm2 start app.js
# With name
pm2 start app.js --name "my-app"
# Cluster mode (use all CPUs)
pm2 start app.js -i max
# List processes
pm2 list
# Monitor
pm2 monit
# Logs
pm2 logs
pm2 logs my-app
# Restart/Stop/Delete
pm2 restart my-app
pm2 stop my-app
pm2 delete my-app
# Restart all
pm2 restart allEcosystem File
code.jsJavaScript
// ecosystem.config.js
module.exports = {
apps: [{
name: 'my-app',
script: './app.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
}]
};$ terminalBash
# Start with ecosystem file
pm2 start ecosystem.config.js --env production
# Save process list for startup
pm2 save
pm2 startupZero-Downtime Reload
$ terminalBash
pm2 reload my-app