Deploy Node to a VPS: nginx Reverse Proxy, PM2, DNS and Let's Encrypt

Node.js and Express: Build a Back End API from Scratch · Testing, Debugging and Deployment · 5 min read · Updated

From browser to Node

  1. The browser asks DNS which IP address your domain points to.
  2. It connects to nginx on port 443. nginx ends the HTTPS and forwards the request.
  3. PM2 keeps several copies of your app running on a private port, and restarts them if they crash.
  4. The app talks to the database, which accepts connections only from this server.

An app that runs only on your laptop helps nobody. This lesson walks the classic route to production: a small rented Linux server, called a VPS (virtual private server), running your app behind nginx with HTTPS on your own domain. It is not the only way, and managed platforms are easier, but this route teaches how the internet actually fits together, and employers like people who have done it once.

The picture

A visitor types your domain. DNS turns the name into the IP address of your server. The browser connects to port 443 where nginx listens. nginx handles HTTPS and passes the request on to your Node app, which listens only on 127.0.0.1:3000, a port that the outside world cannot reach. PM2 keeps the Node app running, restarts it if it crashes and starts it after a reboot. This layout is called a reverse proxy, and it is standard.

Step by step

  1. Rent a server. Pick a small Ubuntu LTS VPS from any provider. Add your SSH key during creation, because passwords are weak.
  2. Log in and update. ssh user@SERVER_IP, then sudo apt update && sudo apt upgrade. Create a normal user for the app, and do not run it as root.
  3. Install Node. Use the NodeSource instructions or a version manager such as nvm, and install a current LTS version of Node.
  4. Firewall. Allow only SSH, HTTP and HTTPS, for example with ufw allow OpenSSH, ufw allow 'Nginx Full' and ufw enable. Do not open port 3000.
  5. Get the code. git clone your repository into /var/www/app, run npm ci --omit=dev, and create the .env file on the server with the production secrets.
  6. Run it with PM2. Install it with npm i -g pm2, start with the config below, then run pm2 save and pm2 startup and follow what it prints, so the app starts after a reboot.
  7. Set up nginx. Install nginx and use the configuration below as a site file.
  8. Point DNS. In your domain provider's panel, add an A record for api (or @) that points to the server IP. It can take from a few minutes to a few hours to spread.
  9. Add HTTPS. Install Certbot and run sudo certbot --nginx -d api.example.com. It gets a free certificate from Let's Encrypt, edits the nginx file and sets automatic renewal.

PM2: keep it alive

// pm2 start ecosystem.config.cjs --env production
module.exports = {
  apps: [
    {
      name: 'api',
      script: './src/server.js',
      instances: 'max',            // one copy per CPU core, using cluster mode
      exec_mode: 'cluster',
      max_memory_restart: '300M',  // restart a copy that leaks memory
      env: { NODE_ENV: 'development', PORT: 3000 },
      env_production: { NODE_ENV: 'production', PORT: 3000 },
      kill_timeout: 10000,         // give open requests time to finish
      listen_timeout: 8000,
    },
  ],
};

instances: 'max' with exec_mode: 'cluster' starts one copy per CPU core, as lesson 18 described. max_memory_restart restarts a copy that grows too big, which is a safety net for a leak, not a cure. pm2 reload restarts the copies one at a time, so users see no downtime, while pm2 restart stops them all briefly. Useful commands are pm2 status, pm2 logs, and pm2 monit.

nginx: the reverse proxy

# /etc/nginx/sites-available/api.example.com
# Replace api.example.com with your domain. Certbot adds the HTTPS parts for you.
upstream node_api {
    server 127.0.0.1:3000;      # add more lines for more copies of the app
    keepalive 16;
}

server {
    listen 80;
    server_name api.example.com;

    client_max_body_size 5m;    # matches the upload limit in the app

    location / {
        proxy_pass http://node_api;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        # needed for WebSockets and Socket.IO
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 60s;
    }
}

The upstream block lists your Node copies. proxy_pass forwards requests to them. The proxy_set_header lines pass the real client address and the original protocol, and this is why the app sets trust proxy in lesson 19. The Upgrade and Connection lines allow WebSockets. client_max_body_size must match the upload limit in your app, or nginx will refuse large uploads with 413 before your code sees them.

Production checklist

  • NODE_ENV=production, real secrets in the environment, and a strong JWT_SECRET.
  • The database allows connections only from your server, not from the whole internet. On MongoDB Atlas, add the server IP to the access list.
  • HTTPS only, with a redirect from port 80. Certbot can do it.
  • Logs go somewhere you can read, with rotation, and pm2 logs is a start.
  • Backups run and a restore has been tested, as lesson 44 explains.
  • A /health route that you can use for monitoring.

Your task

  1. Rent the cheapest server you can, or use a free trial, and follow the steps with a spare domain or a subdomain.
  2. Check the certificate renewal with sudo certbot renew --dry-run.
  3. Open /health from your phone and then run pm2 reload while refreshing the page.

How to check it worked

  • The site opens over HTTPS and port 3000 is not reachable from outside.
  • The app survives a server reboot.
  • You can draw the path from the browser to your Node app.

Frequently asked questions

Why put nginx in front of Node?

It handles HTTPS, compression, static files and buffering very well, and it lets you run several copies of the app behind one address.

Is Let's Encrypt really free?

Yes, the certificates are free. They last 90 days and Certbot renews them automatically.

What is the difference between pm2 restart and pm2 reload?

Restart stops all copies and starts them again. Reload restarts them one at a time, so the app stays available.

Practise with interview questions