Topics Testing, Debugging & Deployment Deployment with PM2 & Docker
intermediate 15 min read

Deployment with PM2 & Docker

Deploy Node.js applications to production using PM2 process manager and Docker containers.

PM2 Process Manager

# Install PM2 globally\nnpm install -g pm2\n\n# Start an application\npm2 start app.js --name my-api\n\n# Start with cluster mode (multi-core)\npm2 start app.js -i max --name my-api\n\n# Common commands\npm2 list                  # List all processes\npm2 logs                  # View logs\npm2 monit                 # Monitor CPU/memory\npm2 restart my-api        # Restart\npm2 stop my-api           # Stop\npm2 delete my-api         # Remove from PM2\n\n# Generate startup script\npm2 startup\npm2 save\n\n# Ecosystem file (ecosystem.config.js)\nmodule.exports = {\n  apps: [{\n    name: 'my-api',\n    script: 'app.js',\n    instances: 'max',\n    exec_mode: 'cluster',\n    env: {\n      NODE_ENV: 'production',\n      PORT: 3000,\n    },\n    env_file: '.env',\n    log_date_format: 'YYYY-MM-DD HH:mm:ss',\n    max_memory_restart: '1G',\n  }],\n};

Docker

# Dockerfile\nFROM node:20-alpine\n\nWORKDIR /app\n\nCOPY package*.json ./\nRUN npm ci --only=production\n\nCOPY . .\n\nEXPOSE 3000\n\nCMD ["node", "app.js"]
# Build and run\n docker build -t my-api .\n docker run -p 3000:3000 -d my-api

Examples

// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'api-server',
    script: './dist/app.js',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: 3000,
    },
    env_file: '.env',
    max_memory_restart: '500M',
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    merge_logs: true,
    autorestart: true,
    watch: false,
    max_restarts: 10,
    restart_delay: 4000,
  }],
};

// Health check endpoint for monitoring
const express = require('express');
const app = express();

app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    pid: process.pid,
    timestamp: new Date().toISOString(),
  });
});

app.listen(process.env.PORT || 3000);

console.log('Production server ready');

Your Notes

Sign in to take notes for this lesson.

Quiz

Testing, Debugging & Deployment Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.