javascriptintermediate

PM2 Process Manager Configuration

PM2 ecosystem file for managing Node.js processes with clustering, log rotation, and auto-restart.

javascript
// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'web-app',
      script: './dist/server.js',
      instances: 'max',
      exec_mode: 'cluster',
      autorestart: true,
      watch: false,
      max_memory_restart: '1G',
      env: {
        NODE_ENV: 'development',
        PORT: 3000,
      },
      env_production: {
        NODE_ENV: 'production',
        PORT: 3000,
      },
      log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
      error_file: './logs/error.log',
      out_file: './logs/output.log',
      merge_logs: true,
      max_restarts: 10,
      restart_delay: 4000,
    },
    {
      name: 'worker',
      script: './dist/worker.js',
      instances: 2,
      autorestart: true,
      max_memory_restart: '512M',
      env_production: {
        NODE_ENV: 'production',
      },
    },
  ],
};

// Start: pm2 start ecosystem.config.js --env production
// Reload: pm2 reload ecosystem.config.js
// Logs: pm2 logs web-app --lines 100

Use Cases

  • Running Node.js in production with clustering
  • Managing multiple application processes
  • Zero-downtime reloads in deployment scripts

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.