📢 LordCloud support has moved to Ballastra — Join now →
VPS & Linux

Deploy a Node.js App on a VPS with Nginx and PM2

A practical walkthrough for putting a Node.js app on a Linux VPS: PM2 for process management, Nginx in front, a firewall and HTTPS.

LordCloud Engineering

Infrastructure & Support Team

Published · 5 min read
On this page

To deploy a Node.js app on a VPS, you run the app under a process manager (PM2), put Nginx in front of it as a reverse proxy, allow only SSH, HTTP and HTTPS through the firewall, and add a TLS certificate. That is the whole recipe, and it works the same for Express, Fastify, NestJS or a Next.js server. This guide walks through each step on Ubuntu, with the commands and the mistakes people usually hit.

You need a Linux VPS with root or sudo access and a domain pointing at its IP. If you do not have a server yet, a Linux VPS with full root access is all this setup requires (see all VPS hosting plans); 1 GB of RAM is enough for a small API.

Why PM2 and Nginx instead of node app.js#

Running node app.js in an SSH session works until you close the terminal, the process crashes, or the server reboots. Then your site is down.

  • PM2 restarts the app if it crashes, keeps logs, and can start it again at boot.
  • Nginx listens on ports 80 and 443, terminates HTTPS, serves static files efficiently and forwards everything else to your app. Your Node process never needs root privileges to bind a low port.

Step 1: Prepare the server#

Log in over SSH, ideally with keys only (see our guide to SSH key login on a Linux VPS), and create a non-root user for the app:

bash
sudo apt update && sudo apt upgrade -y
sudo adduser deploy
sudo usermod -aG sudo deploy

Open the firewall for SSH and web traffic only:

bash
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'   # after nginx is installed; or: ufw allow 80,443/tcp
sudo ufw enable

Do not open port 3000. If you later run Docker, read why published Docker ports bypass UFW.

Step 2: Install Node.js and Nginx#

Pick an LTS release. The Node.js release schedule lists the current LTS lines, and production apps should only use Active LTS or Maintenance LTS versions. Ubuntu's packaged nodejs is often older, so most people use the NodeSource packages or nvm. Follow the install instructions on nodejs.org for your chosen version, then verify:

bash
node -v
npm -v
sudo apt install -y nginx

If you use nvm as the deploy user, remember PM2's startup command later needs the path to that Node binary.

Step 3: Deploy the Node.js app on your VPS#

Clone your repository (or copy it with rsync) into a directory such as /home/deploy/myapp, then install production dependencies and build if needed:

bash
cd /home/deploy/myapp
npm ci --omit=dev

Use npm ci rather than npm install so you get exactly the versions in your lockfile. Keep secrets in an environment file that is not committed to git, and make sure your app reads its port from process.env.PORT and listens on 127.0.0.1.

Step 4: Run the app with PM2#

bash
sudo npm install -g pm2
pm2 start server.js --name myapp
pm2 status
pm2 logs myapp

For anything beyond a single script, use an ecosystem file so the configuration lives in version control:

js
// ecosystem.config.js
module.exports = {
  apps: [{
    name: "myapp",
    script: "server.js",
    env: { NODE_ENV: "production", PORT: 3000 },
    max_memory_restart: "300M"
  }]
};

Start it with pm2 start ecosystem.config.js. max_memory_restart is a useful safety net on small servers: a memory leak restarts the process instead of getting it killed by the kernel.

How do I start PM2 on boot?#

According to the PM2 startup documentation, run pm2 startup without sudo. It detects your init system (systemd on Ubuntu) and prints a command to copy and run. Run that, start your apps, then save the list:

bash
pm2 startup
# run the command it prints, then:
pm2 save

Reboot once to test it. If you upgrade Node.js later, run pm2 unstartup followed by pm2 startup so the boot script points at the new binary.

Step 5: Configure Nginx as a reverse proxy#

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

nginx
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;
    }
}

The directives are documented in the nginx proxy module reference. By default Nginx sends Host as the upstream address, so proxy_set_header Host $host is what keeps your app seeing the real domain. The X-Forwarded-* headers let the app know the client IP and whether the request was HTTPS; in Express, set app.set('trust proxy', 1) to use them.

If your app uses WebSockets (Socket.IO, for example), also add proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection "upgrade";.

Enable the site and reload:

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

Always run nginx -t first; a typo then cannot take down every site on the server.

Step 6: Add HTTPS#

Certbot from Let's Encrypt is the usual route on Ubuntu:

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

Certbot edits the Nginx config, adds the redirect and sets up automatic renewal. Check renewal works with sudo certbot renew --dry-run. Your DNS A record must already point at the VPS or the challenge fails.

Security and resource checklist#

Before calling it done, spend ten minutes on the basics. A public VPS gets automated login attempts within hours of going online, so set up Fail2ban for SSH and disable password logins once keys work.

  • Run as the deploy user, never root. If the app is compromised, the damage is limited to that account's files.
  • Bind to localhost. Listening on 127.0.0.1 means a mistake in the firewall cannot expose the raw Node port.
  • Watch memory. Run free -h and pm2 monit after a day of traffic. Node's heap grows under load, and on a 1 GB server Nginx, the OS and your app share that space. Add a few hundred MB of swap as a buffer, but treat constant swapping as a sign you need a bigger plan.
  • Rotate logs. PM2 logs grow without limit by default. Install the log rotation module with pm2 install pm2-logrotate so a chatty app cannot fill the disk.
  • Keep the OS patched. Enable unattended security upgrades with sudo apt install unattended-upgrades and review /etc/apt/apt.conf.d/20auto-upgrades.
  • Back up what matters. Your code is in git, but databases and uploaded files are not. Copy them off the server on a schedule and test a restore at least once.

Deploying updates#

A simple, safe update routine:

bash
cd /home/deploy/myapp
git pull
npm ci --omit=dev
pm2 reload myapp

pm2 reload does a graceful restart. For zero-downtime reloads you need cluster mode (exec_mode: "cluster", instances: 2), which needs more than one CPU core to be worthwhile.

Troubleshooting#

  • 502 Bad Gateway: Nginx cannot reach your app. Check pm2 status, then curl http://127.0.0.1:3000 on the server. Confirm the port matches proxy_pass.
  • App works by IP:3000 but not by domain: a firewall or DNS issue. Check sudo ufw status and your A record.
  • Process restarts constantly: read pm2 logs myapp --lines 100. Missing environment variables are the most common cause.
  • Gone after reboot: you skipped pm2 save, or Node's path changed after an upgrade.

For background on how services differ, see understanding hosting services, and if you want a hands-off scheduled task rather than a long-running server, compare cron and systemd timers.

Frequently asked questions#

Can I run several Node.js apps on one VPS?#

Yes. Give each app its own port and PM2 name, then add one Nginx server block per domain, each with its own proxy_pass. Watch total RAM across all processes.

Should I use PM2 or systemd?#

Both work. PM2 adds convenient logs, monitoring and reload commands for Node apps. A plain systemd unit has fewer moving parts. Pick one and use it consistently rather than both.

Frequently asked questions

How do I deploy a Node.js app on a VPS?

Install an LTS version of Node.js, copy your code to the server, start it with PM2, put Nginx in front as a reverse proxy on ports 80/443, open only those ports plus SSH in the firewall, and enable HTTPS with a certificate.

Do I need Nginx if I use PM2?

PM2 keeps your process running but does not handle TLS, caching, static files or multiple sites on one port. Nginx in front of it does, and lets your app run on an unprivileged port like 3000.

How do I make PM2 start after a reboot?

Run pm2 startup, copy and run the command it prints, start your apps, then run pm2 save so the process list is restored on boot.

Which port should my Node.js app listen on?

Any unprivileged port such as 3000, bound to 127.0.0.1 so it is only reachable through Nginx, not directly from the internet.

References

Drafted with AI assistance and checked against LordCloud's published product information. Spotted a mistake?Suggest an edit.

All articles →
Have a question? Chat with us👋