SyntaxStudy
Sign Up
Express.js Running Express in Production with PM2
Express.js Beginner 1 min read

Running Express in Production with PM2

PM2 is a production process manager for Node.js that provides automatic restarts on crash, zero-downtime reloads, cluster mode for multi-core utilisation, log management, and monitoring. Install it globally with `npm install -g pm2` and start your app with `pm2 start app.js --name myapp`. PM2 persists across reboots with `pm2 startup` and `pm2 save`. Cluster mode forks the app into as many worker processes as there are CPU cores, distributing incoming connections across them through Node's cluster module. This is essential for CPU-bound workloads and maximises throughput on multi-core servers. Enable it with `pm2 start app.js -i max` or in an `ecosystem.config.js` file. PM2's `ecosystem.config.js` is the recommended way to define app configuration for different environments. It specifies the entry point, instance count, environment variables, log file paths, and watch patterns. Committing this file to version control (without secrets) documents the expected runtime configuration for every developer and CI/CD pipeline.
Example
// ecosystem.config.js  (committed to git, no secrets)
module.exports = {
    apps: [
        {
            name:         'api',
            script:       './server.js',
            instances:    'max',        // one per CPU core
            exec_mode:    'cluster',
            watch:        false,        // disable in production
            max_memory_restart: '512M',
            env: {
                NODE_ENV: 'development',
                PORT:     3000,
            },
            env_production: {
                NODE_ENV: 'production',
                PORT:     8080,
            },
            error_file: './logs/err.log',
            out_file:   './logs/out.log',
            log_date_format: 'YYYY-MM-DD HH:mm:ss',
        },
    ],
};

// Commands:
// pm2 start ecosystem.config.js --env production
// pm2 reload api          # zero-downtime reload
// pm2 logs api            # tail logs
// pm2 monit               # live dashboard
// pm2 startup             # generate startup script
// pm2 save                # save process list