Deploying Node.js Apps with PM2 in Production
Deployment

Deploying Node.js Apps with PM2 in Production

  • AuthorTimothy M.
  • Date
  • Time15 minutes

Step 1: Install Node.js LTS

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

Step 2: Install PM2 Globally

bash
sudo npm install -g pm2
pm2 -v

Step 3: Prepare App and Dependencies

bash
cd /var/www/my-node-app
npm ci
cp .env.example .env

Step 4: Create PM2 Ecosystem File

javascript
cat > ecosystem.config.js <<'EOF'
module.exports = {
  apps: [
    {
      name: 'my-node-app',
      script: 'dist/server.js',
      instances: 'max',
      exec_mode: 'cluster',
      env: {
        NODE_ENV: 'production',
        PORT: 3000
      },
      max_memory_restart: '500M',
      time: true
    }
  ]
};
EOF

Step 5: Start and Inspect Process

bash
pm2 start ecosystem.config.js
pm2 ls
pm2 logs my-node-app --lines 100
pm2 monit

Step 6: Enable Auto-Start on Reboot

bash
pm2 startup systemd -u $USER --hp /home/$USER
pm2 save

Step 7: Configure Log Rotation

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

Step 8: Zero-Downtime Deploy Update

bash
git pull
npm ci
npm run build
pm2 reload ecosystem.config.js --update-env

Step 9: Quick Health Checks

bash
curl -I http://127.0.0.1:3000/health
pm2 show my-node-app

"PM2 gives you operational guardrails, but good deployment hygiene still depends on your release process."

Technical Author

Timothy M.

Timothy M.

Support and server administration. Writes the work on the host: packages, services, and what to check when a machine misbehaves.