How to Run Node.js Apps Behind Nginx with PM2 on a VPS

Running a Node.js app on a VPS sounds simple until the app stops the moment you close your terminal. The fix is a small stack of three parts: Node.js runs your code, PM2 keeps the process alive, and Nginx sits in front as the public face. This guide shows you how to run Node.js apps behind Nginx with PM2 on a VPS, step by step, on Ubuntu 24.04. You need a VPS with a domain pointed at it and a user account with sudo access. If your server is fresh, start with the first-10-things checklist for a new VPS before you install anything.

How the Three Pieces Fit Together

Each part of the stack does one job. Node.js runs your JavaScript on the server, usually listening on a local port such as 3000.

Nginx never runs your code. It only forwards requests. Your app never talks to the internet directly. It only listens on localhost. That split gives you two wins: Nginx can serve HTTPS, compress responses, and block bad traffic, while your app stays simple and only answers requests that already passed through Nginx. An Nginx reverse proxy Node.js setup like this is easy to debug because each layer has one job. If you want the full background first, read what a reverse proxy is and when to use Nginx for it.

How to Run Node.js Apps Behind Nginx: The Setup

Install Node.js from the official NodeSource repository so you get a current LTS version instead of the old one in the Ubuntu archive. These commands install Node.js 22 LTS. Adjust the version number if a newer LTS is out when you read this. Running Node.js on a VPS starts here, with a current runtime and a clean install.

curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs
node -v
npm -v

Check that both commands print version numbers. Then install PM2 globally with npm. The PM2 process manager runs your app in the background, restarts it on crashes, and keeps logs in one place. This is the simplest form of a Node.js production deployment that still covers crashes, reboots, and HTTPS.

sudo npm install -g pm2
pm2 -v

Now put your app on the server. The example below uses a small Express app, but any Node.js app that listens on a port works the same way. Clone your project or copy the files into a directory such as /var/www/myapp, then install its dependencies.

cd /var/www/myapp
npm install --omit=dev
cp .env.example .env

Open .env and set the port and any secrets your app needs. Keep secrets in this file and never commit them to git. Start the app with PM2, giving the process a clear name.

pm2 start app.js --name myapp
pm2 status

PM2 should show your app as online. Test it directly, before Nginx enters the picture, with a request to the local port.

curl http://localhost:3000

If that returns your app’s output, Node.js and PM2 are working. If it fails, fix the app first. Adding Nginx on top of a broken app only makes the error harder to trace.

Point Nginx at Your App

Install Nginx if it is not on the server yet, then create a server block for your domain. This block listens on port 80 and forwards traffic to the port your app uses. The proxy headers matter: without them, your app sees every visitor as 127.0.0.1 and loses the real IP address, and redirects can point at the wrong scheme.

sudo apt install -y nginx
sudo nano /etc/nginx/sites-available/myapp
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 Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass $http_upgrade;
    }
}

The two lines with Upgrade and Connection let WebSocket connections pass through. Skip them if your app has no live features, but keep them if it uses Socket.io or any realtime channel. Enable the site and test the config before you reload Nginx. This test catches typos without touching the live server.

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

Run nginx -t every time you edit a config file. A reload with a broken config can take Nginx down, while the test takes one second and costs nothing. For a deeper walkthrough of the same pattern, see the step-by-step Nginx reverse proxy tutorial. If you run several sites on one server, the same structure applies to each one. Our guide to setting up Nginx server blocks on Ubuntu 24.04 covers that layout in detail.

Add Free HTTPS with Certbot

Your app now works over plain HTTP. Add HTTPS before you share the URL with anyone. Certbot gets a free certificate from Let’s Encrypt and rewrites your Nginx config to use it.

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

Certbot asks a few questions, then sets up a redirect from HTTP to HTTPS and adds a renewal timer. Test the renewal with a dry run so you find out now, not on the day the certificate expires.

sudo certbot renew --dry-run

Visit your domain in a browser and check for the lock icon. If the page loads over HTTPS and your app answers, the full chain works. For the full process including DNS checks, see how to install a free Let’s Encrypt certificate on Nginx with Certbot.

Keep the App Alive After a Reboot

PM2 restarts a crashed app, but a server reboot wipes the process list unless you tell PM2 to restore it. Run the startup command once and follow the command it prints. On Ubuntu that is usually a systemctl command.

pm2 startup
pm2 save

The first command creates a service that starts PM2 at boot. The second saves your current process list so PM2 knows what to bring back. Test it the honest way: reboot the server, wait a minute, then check the status.

sudo reboot
pm2 status
curl https://example.com

If the app shows as online after the reboot, your setup survives restarts. If it does not, run pm2 startup again and read the exact command it prints. Copying that command wrong is the most common reason the restore fails.

Common Problems and Fixes

Most failures in this stack show up as a 502 Bad Gateway page. That error means Nginx is running but cannot reach your app. Work through the causes in order instead of guessing.

Symptom Likely cause Fix
502 Bad Gateway App not running Run pm2 status and pm2 restart myapp
502 Bad Gateway Wrong port in the config Match proxy_pass to the port in your app
502 after a deploy Old process still holds the port Run pm2 restart myapp after each deploy
Site shows the Nginx welcome page Default site still enabled Remove the default symlink from sites-enabled
App restarts in a loop Crash on startup, bad env value Read pm2 logs myapp and fix the error

Logs are your first stop for any of these. PM2 keeps app logs, and Nginx keeps its own error log. Check both before you change a config file.

pm2 logs myapp --lines 50
sudo tail -50 /var/log/nginx/error.log

If the 502 keeps coming back, the guide to fixing 502 Bad Gateway errors in Nginx walks through each cause with more detail.

A Few Habits That Save You Later

Deploy with a restart, not a fresh start. After you pull new code, install dependencies and restart the PM2 process so the new code actually loads.

cd /var/www/myapp
git pull
npm install --omit=dev
pm2 restart myapp

Give each app its own port and its own PM2 name. When two apps share a port, the second one fails to start and the error message rarely says why. A short list of ports in a text file beats debugging a port clash at midnight.

Open only the ports you need in the firewall. Port 80 and 443 stay open for the public. Your app port, 3000 in this example, should stay closed to the outside world. Nginx reaches it over localhost, so nobody else needs access to it.

sudo ufw allow 'Nginx Full'
sudo ufw allow OpenSSH
sudo ufw enable

Check the firewall status after you enable it. If you run these commands over SSH, allow OpenSSH first, or you can lock yourself out of your own server.

That is the whole setup. Node.js runs your code, PM2 keeps it running, and Nginx puts it on the internet with HTTPS. The same pattern scales to more apps: one more port, one more PM2 process, one more server block. Start with one app, get it stable, then repeat the pattern.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.