Node.js VPS Production Setup: NODE_ENV, Cluster Mode, PM2 & Nginx

A step-by-step Node.js production setup for a VPS: environment flag, multi-process cluster, zero-downtime reloads with PM2, and Nginx in front.

Running Node.js in production on a VPS comes down to four decisions: set NODE_ENV=production, use more than one process, let a process manager restart and reload the app, and put Nginx in front for TLS and static files. This guide walks through each, with commands you can run on a fresh StreamData KVM VPS.

Prerequisites

  • A Linux VPS with sudo access and a non-root user for the app. A KVM VPS with 2 GB of RAM or more is a sensible start for a small API.
  • Node.js installed (an LTS release), and your application in a Git repository.
  • A domain pointing at the server's IP address.

Step 1: Set NODE_ENV to production

The Node.js learning guide on development versus production makes a point that surprises many people: Node.js has no built-in settings that switch between modes, and nothing extra is needed to run it in production. What changes is the libraries. Some npm packages read NODE_ENV and fall back to development behaviour when it is unset, so the guide recommends always running with it set:

NODE_ENV=production node app.js

The same page calls it an antipattern to set NODE_ENV to anything other than production, such as staging, because then the code paths you test differ from the ones you run. Keep other differences in configuration read from the environment.

Step 2: Use every CPU with the cluster module

A single Node.js process uses one CPU core for JavaScript. The cluster module in the official API documentation lets one primary process fork workers that share a server port. The documented example forks one worker per value of os.availableParallelism():

import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';

if (cluster.isPrimary) {
  for (let i = 0; i < availableParallelism(); i++) cluster.fork();
  cluster.on('exit', () => cluster.fork());
} else {
  http.createServer((req, res) => res.end('ok\n')).listen(8000);
}

Several caveats from the same page matter in production:

  • Round-robin scheduling is the default on every platform except Windows. The alternative, leaving distribution to the operating system, can be badly unbalanced; the page cites a case where over 70 percent of connections landed on two of eight processes.
  • Workers do not share memory, so avoid keeping sessions or login state in process memory.
  • Nothing respawns dead workers for you. If none are alive, new connections are refused, so your own code or a process manager must restart them.
  • worker.disconnect() does not wait for client connections to close, so use a timeout during shutdown.

Step 3: Let PM2 run the cluster

You do not have to write the cluster code yourself. PM2's cluster mode documentation shows that pm2 start app.js -i max spreads a networked Node.js app across all CPUs without code changes, where -1 means all CPUs minus one. In an ecosystem file:

module.exports = {
  apps: [{
    name: 'api',
    script: 'app.js',
    instances: 'max',
    exec_mode: 'cluster',
    env_production: { NODE_ENV: 'production', PORT: 8000 }
  }]
};
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup systemd

Deploy new versions with pm2 reload api rather than restart. The documentation says reload provides zero-downtime restarts and falls back to a classic restart if the reload does not complete in time. It also tells you to catch SIGINT to finish pending work and close database connections, and to keep the app stateless, with sessions and shared state in Redis or MongoDB.

Step 4: Put Nginx in front

Let Nginx hold ports 80 and 443, terminate TLS and serve static files, and proxy everything else to the Node.js port on localhost:

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

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Bind Node.js to 127.0.0.1 so the app cannot be reached except through the proxy, and issue a certificate with your preferred ACME client. If your framework builds absolute URLs, configure it to trust the forwarded headers.

Verify

pm2 status
curl -I https://api.example.com/
sudo reboot   # then check pm2 status again

Common errors

  • 502 Bad Gateway: the app is not listening on the port Nginx expects; check pm2 logs.
  • Users logged out at random: sessions in process memory with several workers; move them to Redis.
  • Memory climbs until restart: set a memory restart threshold in PM2 and profile the leak.
  • App dies after logout: you skipped pm2 startup and pm2 save.

Outgrowing one machine is a good problem. A larger plan, a second VPS behind a load balancer, or a dedicated server are the usual next steps.


Sources