Skip to content
Go back

Scaling Node.js on VPS with PM2 + Nginx

Scaling Node.js on VPS with PM2 + Nginx

Introduction

Using PM2 for process management and Nginx as a reverse proxy provides high availability and load balancing for Node.js apps on a VPS.

Prerequisites

Step 1: Install PM2

npm install -g pm2

Step 2: Start App with PM2

pm2 start app.js --name myapp
pm2 save
pm2 startup systemd

Step 3: Configure Nginx

Create /etc/nginx/sites-available/myapp:

upstream myapp {
  server 127.0.0.1:3000;
  server 127.0.0.1:3001;
  server 127.0.0.1:3002;
}

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://myapp;
    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;
  }
}

Enable and reload Nginx:

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Step 4: PM2 Cluster Mode

Restart app in cluster mode:

pm2 delete myapp
pm2 start app.js -i max --name myapp
pm2 save

This starts as many instances as CPU cores.

Summary

Combining PM2 in cluster mode with Nginx upstream load balancing ensures your Node.js app runs across multiple cores with automatic restarts and reverse proxying for production readiness.


Share this post on:

Previous Post
Automating Workflows with n8n and Stripe
Next Post
Using Docker Secrets for Managing Credentials