Linux

Managing Node.js applications with PM2

ColossusCloud's Team 2 min read

What is PM2?

PM2 is a production process manager for Node.js applications. It keeps apps running 24/7 by:

  • Auto-restarting when apps crash
  • Starting on boot when servers restart
  • Clustering to use all CPU cores
  • Log management with rotation
  • Monitoring CPU and memory usage

Prerequisites

Step 1: Install PM2

sudo npm install -g pm2
pm2 --version

Step 2: Start application

Navigate to application directory and start with PM2:

cd /home/youruser/myapp
pm2 start app.js --name myapp

The --name flag gives apps friendly names for management.

Step 3: Configure auto-restart on boot

pm2 startup

PM2 outputs a command to run. Copy and execute it:

sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u youruser --hp /home/youruser

Save current process list:

pm2 save

Apps now start automatically when servers boot.

Step 4: Basic PM2 commands

# List all running applications
pm2 list

# Show detailed info
pm2 show myapp

# Restart application
pm2 restart myapp

# Stop application
pm2 stop myapp

# Delete from PM2
pm2 delete myapp

# View logs
pm2 logs myapp

# Monitor CPU/memory in real-time
pm2 monit

Step 5: Enable cluster mode

Node.js runs single-threaded by default. Cluster mode spawns multiple instances using all CPU cores:

pm2 start app.js --name myapp -i max

-i max spawns one instance per CPU core.

Scale already running apps:

pm2 scale myapp 4

Step 6: Use ecosystem file

For complex configurations:

pm2 ecosystem

Edit ecosystem.config.js:

module.exports = {
  apps: [{
    name: 'myapp',
    script: 'app.js',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'development',
      PORT: 3000
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    max_memory_restart: '500M',
    log_date_format: 'YYYY-MM-DD HH:mm:ss'
  }]
}

Start with ecosystem file:

pm2 start ecosystem.config.js --env production

Step 7: Log management

Set up log rotation:

pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
pm2 set pm2-logrotate:compress true

Step 8: Zero-downtime reloads

For deploying updates with zero downtime:

pm2 reload myapp

This restarts instances one by one, keeping apps available throughout.


Explore VPS plans for reliable Node.js hosting.

Choose your VPS.

Compare CPU types, memory, and storage to find the right configuration.

Explore VPS plans