Node.js PM2 Deployment Guide

Install Node.js, run apps with PM2, and keep services resilient across reboots.

Back to Guides ยท Home

What this guide covers: Node.js LTS install, PM2 setup, startup integration, and common production troubleshooting.

Best for: API services, web apps, and worker processes on Linux VPS or dedicated servers.

1. Install Node.js LTS

Ubuntu / Debian

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
node -v
npm -v

Rocky / AlmaLinux / CentOS

curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo dnf install -y nodejs
node -v
npm -v

2. Install PM2

sudo npm install -g pm2
pm2 -v

3. Run Your App with PM2

# Start app
pm2 start app.js --name myapp

# Or run npm start
pm2 start npm --name myapp -- start

# View process list
pm2 list

# Show logs
pm2 logs myapp

4. Persist Processes Across Reboot

# Save current process list
pm2 save

# Generate startup script
pm2 startup

# Run the printed sudo command, then save again
pm2 save

5. Recommended ecosystem.config.js

module.exports = {
  apps: [
    {
      name: "myapp",
      script: "app.js",
      instances: 1,
      exec_mode: "fork",
      watch: false,
      max_memory_restart: "300M",
      env: {
        NODE_ENV: "production",
        PORT: 3000
      }
    }
  ]
};
pm2 start ecosystem.config.js
pm2 save

6. Zero-Downtime Reload (Cluster Mode)

# In ecosystem config, use:
# instances: "max"
# exec_mode: "cluster"

pm2 reload myapp

7. Common Operations

pm2 restart myapp
pm2 stop myapp
pm2 delete myapp
pm2 monit
pm2 logs --lines 200
pm2 flush

8. Troubleshooting

Issue Typical Cause Fix
App restarts repeatedly Unhandled exception or env var missing Check pm2 logs, verify env values and startup command
Port already in use Another process binds the same port Find conflicting process and change port or stop old service
Process missing after reboot pm2 save or startup setup not completed Run pm2 startup, execute printed command, then pm2 save