Deployment & PM2

Deploying a Node.js application is different from static sites. Since it's a server, you need to ensure it's always running, handles traffic efficiently, and restarts automatically if it crashes.

1. Process Management with PM2

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

# Install PM2 globally
npm install pm2 -g

# Start an application
pm2 start app.js --name "my-api"

# Monitor apps
pm2 list
pm2 monit

# Stop and Delete
pm2 stop my-api
pm2 delete my-api

# Restart automatically on server reboot
pm2 startup
pm2 save

2. Hosting Platforms

  • PaaS (Platform as a Service): Easiest way to deploy. Examples: Vercel, Render, Heroku. They handle the server environment for you.
  • IaaS (Infrastructure as a Service): For full control. Examples: AWS (EC2), DigitalOcean, Google Cloud. You manage the OS and Node.js installation.

3. Production Checklist

  1. Security: Use helmet middleware to set secure HTTP headers.
  2. Gzip Compression: Use compression middleware to reduce response body size.
  3. Environment Variables: Ensure NODE_ENV is set to production.
  4. Logging: Use Winston or Morgan to log to files, not just the console.
  5. Reverse Proxy: Use Nginx in front of Node.js for SSL and load balancing.

4. Zero-Downtime Deployment

When you update your code, you don't want your users to see a "502 Bad Gateway" error. Use PM2's reload command to update the application without interrupting connections:

pm2 reload all
Congratulations! You've completed the Node.js Masterclass. You are now ready to build and deploy professional, scalable backends.