Production Deployments with PM2 & Nginx

🦁 Express.jsLesson 15Advanced

Deploying Express applications in production requires process managers to handle background daemon processes, auto-restarts, and load-balancing proxies.

1 Setting up PM2 Process Manager

PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever:

Shell — Running PM2
# Install PM2 globally
npm install pm2 -g

# Start your application in cluster mode across all available cores
pm2 start index.js -i max --name "express-api"

# View daemon processes list and system metrics
pm2 list
pm2 monit
2 Configuring Nginx Proxy Pass

Nginx acts as a reverse proxy, forwarding external internet requests to the local Express app running behind your firewall:

Nginx — /etc/nginx/sites-available/default
server {
  listen 80;
  server_name yourdomain.com;

  location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}
3 Code Challenge
Challenge: Write a basic ecosystem.config.js PM2 launch file that configures application environment variables and auto-restart properties for deployment.