SyntaxStudy
Sign Up
Node.js Beginner 10 min read

PM2 Process Manager

PM2 is a production process manager for Node.js. It keeps your app alive, restarts it on crashes, manages logs, and can run multiple app instances using cluster mode to take advantage of multi-core CPUs.

Example
# Install PM2 globally:
npm install -g pm2

# Start your app:
pm2 start app.js --name "my-api"

# Start in cluster mode (use all CPU cores):
pm2 start app.js --name "my-api" -i max

# List running processes:
pm2 list

# Show logs:
pm2 logs my-api

# Restart / stop / delete:
pm2 restart my-api
pm2 stop    my-api
pm2 delete  my-api

# Auto-restart on server reboot (generates startup script):
pm2 startup
pm2 save

# ecosystem.config.js — configuration file for PM2:
# module.exports = {
#   apps: [{
#     name:         'my-api',
#     script:       'src/index.js',
#     instances:    'max',
#     exec_mode:    'cluster',
#     env:          { NODE_ENV: 'development', PORT: 3000 },
#     env_production: { NODE_ENV: 'production', PORT: 8080 },
#   }]
# };
#
# pm2 start ecosystem.config.js --env production