العربية

Deploy a Node.js app on a VPS with PM2 and Nginx, step by step

A practical walkthrough for running Node.js in production on your own server: PM2 for restarts, Nginx in front, environment files, zero-downtime reloads and a small rsync deploy script.

· 6 min read
Deploy a Node.js app on a VPS with PM2 and Nginx, step by step

Your Node.js app runs fine on your laptop with npm start. Then you put it on a server, close the terminal, and the site goes down. This guide shows how to deploy Node.js on a VPS the way I deploy this site: PM2 keeps the app alive, Nginx sits in front of it, and one script ships each update.

This site and its blog run on a Hostinger VPS with Ubuntu 22.04, Node.js under PM2, MySQL in Docker and Nginx. The steps below follow that setup, with placeholders in place of real names.

What you need before you deploy Node.js on a VPS

  • A VPS running Ubuntu (22.04 in my case) and SSH access with a key, not a password. hPanel on Hostinger lets you add SSH keys, and it has a browser terminal if you get locked out.
  • A domain pointing to the server's IP. If you haven't done that yet, read how to point your domain to Hostinger.
  • A firewall that allows only SSH (22), HTTP (80) and HTTPS (443). Your Node port should never be open to the internet.

If you are still deciding whether you need a VPS at all, shared hosting or VPS covers that choice. A VPS gives you full control. It also means updates, backups and security are your job.

Install Node.js from NodeSource (replace 20 with the current LTS version) and PM2:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs nginx
sudo npm install -g pm2
node -v && pm2 -v

Run the app with PM2: restart on crash and on reboot

PM2 is a process manager. It starts your app in the background, restarts it if it crashes, and keeps logs. Put the settings in a file instead of long commands, so they live in your repository.

Create ecosystem.config.js in your project root:

module.exports = {
  apps: [
    {
      name: "my-app",
      script: "server.js",
      cwd: "/var/www/my-app",
      instances: 2,
      exec_mode: "cluster",
      max_memory_restart: "300M",
      env: {
        NODE_ENV: "production",
        PORT: 3000
      }
    }
  ]
};

Start it, then tell PM2 to come back after a reboot:

cd /var/www/my-app
pm2 start ecosystem.config.js
pm2 save
pm2 startup systemd

pm2 startup prints a command that starts with sudo env PATH=.... Copy it and run it exactly as printed. From then on, whatever you saved with pm2 save starts when the server boots.

A few commands you will use every day:

pm2 status
pm2 logs my-app --lines 100
pm2 monit

Logs grow forever by default. Install the rotation module once and forget about it:

pm2 install pm2-logrotate

Keep secrets in an environment file

Database passwords, API keys and SMTP credentials do not belong in Git. Keep them in a .env file that lives only on the server:

# /var/www/my-app/.env
DB_HOST=127.0.0.1
DB_USER=your-user
DB_PASSWORD=change-me
SMTP_HOST=smtp.example.com

Load it at the very top of your entry file with the dotenv package:

require("dotenv").config({ path: __dirname + "/.env" });

Lock the file down so only your user can read it:

chmod 600 /var/www/my-app/.env

Non-secret settings like NODE_ENV and PORT can stay in the ecosystem file. Secrets stay in .env. The deploy script later in this article never touches that file.

Nginx as a reverse proxy in front of Node

Your app listens on port 3000, bound to localhost only. Nginx listens on 80 and 443, handles HTTPS, and forwards requests to Node. This is the standard PM2 and Nginx pairing, and it keeps your app off the public internet.

First, make Node listen on localhost:

const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, "127.0.0.1");

Then create /etc/nginx/sites-available/my-app:

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

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

Enable it, test, and reload:

sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Now add HTTPS with Certbot. On this site I did it for the root domain, www and the blog subdomain, and renewal runs automatically:

sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run

If you use Express, add app.set("trust proxy", 1); so req.ip and secure cookies work correctly behind Nginx.

Zero-downtime reload with PM2 cluster mode

pm2 restart stops the app, then starts it. For a second or two, visitors get errors. pm2 reload is different: in cluster mode it replaces workers one at a time, so one is always serving requests. That is why the ecosystem file above uses exec_mode: "cluster" with two instances. In fork mode, reload behaves like a restart.

For a clean handover, let each worker finish its current requests before it exits. PM2 sends SIGINT first:

process.on("SIGINT", () => {
  server.close(() => process.exit(0));
});

Then deploy updates with:

pm2 reload ecosystem.config.js --update-env

One caution: cluster mode runs several copies of your app. Anything kept in memory, such as sessions or a simple cache, is not shared between them. Store sessions in the database or Redis.

A simple deploy script with rsync

You don't need a full CI pipeline to start. This script builds locally, uploads only what changed, installs production dependencies, and reloads PM2. Save it as deploy.sh in your project:

#!/usr/bin/env bash
set -euo pipefail

SERVER="your-user@203.0.113.10"
APP_DIR="/var/www/my-app"

echo "Building..."
npm ci
npm run build

echo "Uploading..."
rsync -az --delete \
  --exclude ".git" \
  --exclude "node_modules" \
  --exclude ".env" \
  ./ "$SERVER:$APP_DIR/"

echo "Installing and reloading..."
ssh "$SERVER" "cd $APP_DIR && npm ci --omit=dev && pm2 reload ecosystem.config.js --update-env"

echo "Deployed."

Make it executable and run it:

chmod +x deploy.sh
./deploy.sh

Notes from real use:

  • Remove npm run build if your app has no build step.
  • --delete removes files on the server that no longer exist locally. Excluded paths like .env are protected, which is exactly what you want.
  • If you installed Node with nvm instead of NodeSource, the non-interactive SSH session may not find pm2. Use the full path or load nvm in the command.
  • Run a quick --dry-run on rsync the first time to see what it will touch.

FAQ

What is the best Node.js hosting for a small project?

Any VPS where you get root access works. A managed platform is easier but gives you less control. I use Hostinger for this site; whichever host you choose, check current prices yourself, since renewal prices are usually higher than the first term. My full notes are in Hostinger from real use.

Do I need Nginx if PM2 already runs my app?

Yes, in practice. PM2 keeps the process alive. Nginx handles HTTPS, domain routing and slow clients, and lets you keep Node bound to localhost.

What is the difference between pm2 restart and pm2 reload?

Restart kills and starts all processes, so there is a short outage. Reload swaps cluster workers one by one, so the app stays up.

How many PM2 instances should I run?

Start with two, so reload can keep one serving. Go higher only if you have the CPU cores and memory, and watch pm2 monit after the change.


Want help putting your app into production? Talk to the editor at ahmed-adil.com.

Some links in this article are affiliate links; if you buy through them, Ahmed may earn a commission at no extra cost to you.

More from the Supplement