Back to Blog

How to Deploy a Node.js App with PM2 and Nginx

How to deploy a Node.js app on a Linux VPS: Node.js LTS, npm ci, PM2 with autostart and reload, an Nginx reverse proxy, HTTPS, updates and common errors.

Nodesty Team11 min readServers
The words Node.js Deploy with PM2 and Nginx on a dark Nodesty background

To deploy a Node.js app to production, running node server.js in an SSH session isn't enough: the app stops when the session closes, stays down after a crash and doesn't come back after a reboot. The usual setup on a Linux VPS is PM2 as the process manager that keeps the app running and Nginx in front as a reverse proxy for HTTPS and WebSocket connections. Once this setup is in place, every update comes down to a handful of commands.

This guide walks through deploying a Node.js application such as an Express API on a clean Ubuntu server: installing Node.js LTS, a separate user, npm ci, environment variables, PM2 with autostart and cluster mode, the Nginx reverse proxy, the firewall, HTTPS, updates and the most common errors.

Requirements

  • Server: An Ubuntu server with root access. In this guide we use Ubuntu 24.04.
  • Application: A Node.js project in a Git repository with package.json and package-lock.json.
  • Domain: An A record pointing to your server's IP address.

A bot that doesn't serve HTTP needs no Nginx; for that case, see our How to host a Discord bot 24/7 guide.

Step 1: Node.js LTS, PM2 and Nginx

After connecting to your server with SSH:

sudo apt update
sudo apt install nginx git curl
curl -fsSL https://deb.nodesource.com/setup_lts.x -o nodesource_setup.sh
sudo -E bash nodesource_setup.sh
sudo apt install nodejs
sudo npm install -g pm2
node -v && npm -v && pm2 -v

Ubuntu 24.04's own repositories ship Node.js 18, which has reached end of life. The NodeSource repository installs the current LTS release system-wide as /usr/bin/node, together with npm; to stay on one major version, replace setup_lts.x with for example setup_24.x. We prefer this over nvm on servers: nvm installs Node.js inside one user's home folder, which makes paths for services and autostart harder to get right.

On AlmaLinux, run curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash - and then sudo dnf install nodejs nginx git. Nginx runs as the nginx user there and site files go in /etc/nginx/conf.d/. See our How to install Nginx guide for the basics.

Step 2: User, code and npm ci

Don't run the application as root. Create a user for it and a folder under /srv:

sudo adduser --disabled-password --gecos "" deploy
sudo mkdir -p /srv/app
sudo chown deploy:deploy /srv/app
sudo -iu deploy
git clone git@github.com:user/app.git /srv/app
cd /srv/app
npm ci
npm run build   # only if your project has a build step

npm ci deletes node_modules and installs exactly the versions recorded in package-lock.json, so the server gets the same packages you tested with; it stops with an error if the lock file and package.json don't match. If the project has no build step, npm ci --omit=dev skips the development dependencies. We cover deploy keys in our How to deploy with Git guide and managing users in How to add a user on Linux. Run the commands in the next steps as the deploy user unless they start with sudo.

Step 3: Environment variables and the listen address

Keep secrets out of the code and the repository. Create /srv/app/.env, add it to .gitignore and protect it with chmod 600 .env:

SESSION_SECRET=paste-a-long-random-value-here
DATABASE_URL=postgres://app:a-strong-password@127.0.0.1:5432/app

openssl rand -hex 32 generates a suitable random value. Node.js 20.6 and later can load this file with the --env-file flag, so you don't need an extra package; if your project already uses dotenv, that works too. Read the values with process.env and make the app listen on the local address only:

const port = Number(process.env.PORT) || 3000;

app.set('trust proxy', 1); // Express: trust the X-Forwarded-* headers set by Nginx
app.listen(port, '127.0.0.1');

Without a host argument, Node.js listens on all interfaces, so the app would also answer on http://SERVER-IP:3000, past Nginx and without HTTPS. Now test it:

node --env-file=.env server.js

From a second SSH session, curl -I http://127.0.0.1:3000 should return a response. Stop the app with Ctrl+C.

Step 4: Run the app with PM2

Describe the app in /srv/app/ecosystem.config.js, so the settings live in a file instead of a long command:

module.exports = {
    apps: [
        {
            name: 'app',
            script: 'server.js',
            cwd: '/srv/app',
            node_args: '--env-file=.env',
            env: {
                NODE_ENV: 'production',
                PORT: 3000,
            },
        },
    ],
};
pm2 start ecosystem.config.js
pm2 status

If your package.json contains "type": "module", name the file ecosystem.config.cjs instead. The commands you'll use most:

CommandWhat it does
pm2 statusLists the processes with their status, restart count (↺) and memory
pm2 logs appFollows the app's output live; the files are in ~/.pm2/logs/
pm2 reload appStarts the new code; in cluster mode one process at a time
pm2 restart appStops and starts all processes of the app at once
pm2 stop app / pm2 delete appStops the app / removes it from PM2's list
pm2 monitShows CPU, memory and logs live in the terminal

Two things are worth knowing:

  • Environment: PM2 remembers the env values from the first start. After changing them, run pm2 reload ecosystem.config.js --update-env; pm2 reload app alone keeps the old values. The .env file is read again on every start, so a normal reload is enough there.
  • Logs: PM2's log files grow without limit. pm2 install pm2-logrotate adds automatic rotation, so they don't end up filling the disk.

Step 5: Start on boot

PM2 itself must start when the server boots and bring your apps back. Save the process list as deploy, then go back to your admin account and register PM2 as a systemd service for that user:

pm2 save
exit
sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u deploy --hp /home/deploy

pm2 startup creates and enables a service called pm2-deploy; at boot it restores the list that pm2 save wrote to /home/deploy/.pm2/dump.pm2. Run pm2 save again whenever you add or remove an app. To be sure, reboot once with sudo reboot and check pm2 status as deploy. If you'd rather manage the app with systemd alone, see our How to create a systemd service guide.

Step 6: Cluster mode

A Node.js process runs your JavaScript on a single CPU core. In cluster mode, PM2 starts several copies of the app that share the same port. Add two lines to the app entry in ecosystem.config.js:

instances: 'max',
exec_mode: 'cluster',

max starts one process per CPU core; you can also write a number. Switching modes needs a fresh start: pm2 delete app, then pm2 start ecosystem.config.js and pm2 save. From then on pm2 reload app replaces the processes one by one, without downtime.

  • No state in memory: Sessions, caches or rate-limit counters kept in a variable exist once per process. Move them to the database or to Redis. Socket.IO additionally needs sticky sessions when several instances run.
  • Clean shutdown: On a reload, PM2 sends SIGINT to the old process and kills it after 1.6 seconds by default (kill_timeout). Handle the signal to finish open requests and close database connections.
  • Memory: Every instance uses its own RAM. If the app does little CPU work, one or two instances are often enough.

Step 7: Nginx reverse proxy

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

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    client_max_body_size 20M;

    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;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}
sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
  • Proxy headers: Host, X-Real-IP, X-Forwarded-For and X-Forwarded-Proto tell the app which domain was requested, who the visitor is and whether the request came over HTTPS. Without them, every request looks like plain HTTP from 127.0.0.1.
  • WebSocket: proxy_http_version 1.1 with the Upgrade and Connection headers lets WebSocket connections (Socket.IO, live updates) pass through. The map block sends Connection: upgrade only when the browser asks for it.
  • Timeouts: Nginx closes a proxied connection that stays silent for 60 seconds (proxy_read_timeout). For WebSockets, send regular ping messages or raise the value.
  • client_max_body_size: Nginx allows 1 MB uploads by default; larger requests get a 413 error.
  • 127.0.0.1 instead of localhost: localhost also resolves to the IPv6 address ::1, where the app isn't listening.

On AlmaLinux, save the file as /etc/nginx/conf.d/app.conf and allow Nginx to connect to local ports with sudo setsebool -P httpd_can_network_connect 1; otherwise SELinux blocks the proxy and you get a 502 error.

Step 8: Firewall and HTTPS

Open only SSH and the web ports. Port 3000 stays closed:

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

If SSH runs on a different port, allow that port before you enable the firewall, or you'll lock yourself out. See our How to use UFW guide. On AlmaLinux, use sudo firewall-cmd --permanent --add-service=http --add-service=https followed by sudo firewall-cmd --reload. Then get the certificate:

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

Certbot gets the certificate, adds the HTTPS server block and sets up automatic renewal. See our What is an SSL certificate? article for details.

Deploying updates

sudo -iu deploy
cd /srv/app
git pull
npm ci
npm run build   # only if your project has a build step
pm2 reload app

The running processes keep the old code in memory until the reload. Afterwards, check pm2 status and pm2 logs app --lines 50: a restart count (↺) that keeps rising means the new version crashes on start. Since npm ci rebuilds node_modules while the old version is still running, larger projects build each release in its own folder; our How to deploy with Git guide shows that approach and a deploy script. Back up the database before migrations that change data; see our server backups guide.

Logs and common errors

The app's output is in pm2 logs app, and Nginx writes to /var/log/nginx/error.log.

ErrorCommon cause
502 Bad GatewayThe app isn't running or keeps crashing (errored in pm2 status), or proxy_pass uses the wrong port
EADDRINUSE: address already in useAnother process holds port 3000, often a node server.js started by hand or a second PM2 run as root
Site opens on http://SERVER-IP:3000The app listens on 0.0.0.0 or :: instead of 127.0.0.1 and the firewall is open
EACCES: permission denied on listenThe app tries to use a port below 1024 as a normal user; use 3000 and let Nginx handle 80 and 443
EACCES in npm ci or when writingFiles belong to root after a sudo npm or sudo git pull
Cannot find modulenpm ci wasn't run after the update, or cwd points to the wrong folder
App is gone after a rebootpm2 startup was never set up, or pm2 save wasn't run after the last change
  • Port in use: sudo ss -tlnp | grep :3000 shows which process holds the port. Our address already in use guide covers the rest.
  • 127.0.0.1 or 0.0.0.0: With Nginx on the same server, 127.0.0.1 is correct. Only if the app runs in a Docker container or Nginx is on another server does it have to listen on 0.0.0.0; then restrict the port with the firewall.
  • Permissions: Fix ownership with sudo chown -R deploy:deploy /srv/app. Don't run sudo pm2 ... for daily work: that starts a second PM2 as root with its own process list in /root/.pm2, and the two fight over the same port.

For a step-by-step 502 checklist, see our 502 Bad Gateway guide.

A note on Next.js, Nuxt and NestJS

Frameworks with a build step work the same way: run npm run build, then point script at the built server. For NestJS that is dist/main.js, for Nuxt .output/server/index.mjs (it reads the HOST and PORT variables), and for Next.js node_modules/next/dist/bin/next with args: 'start -H 127.0.0.1 -p 3000'. The shortcut pm2 start npm --name app -- start runs the start script from package.json, but it isn't suitable for cluster mode, because PM2 then manages npm rather than your app. Nginx and HTTPS stay the same.

Nodesty servers for Node.js apps

Nodesty AMD Ryzen 9 9950X VPS plans give Node.js, which runs your code on a single core per process, low response times with high single-core speed, while AMD EPYC 7763 VPS plans offer plenty of cores and RAM for PM2 cluster mode, the database and background jobs on the same server. With full root access, NVMe storage, nShield DDoS protection and free daily backups kept for 7 days, you can deploy your Express, NestJS or Next.js projects with confidence.

Frequently Asked Questions

Why not just run node server.js or npm start on the server?

A process started by hand stops when you close the SSH session, stays down after a crash and doesn't come back after a reboot. A process manager like PM2 runs the app in the background, restarts it when it crashes, collects its logs and starts it again when the server boots.

Should I use PM2 or systemd for a Node.js app?

Both keep the app running and start it on boot. PM2 adds Node.js specific conveniences such as cluster mode, reloads without downtime and its own log view. systemd is already part of the system and works the same for every language. PM2 itself uses a small systemd service to start at boot.

Do I need Nginx in front of a Node.js app?

Node.js can answer HTTP requests on its own, but Nginx in front takes over ports 80 and 443, HTTPS certificates, several sites on one server, upload limits and slow clients. Your app then runs as a normal user on a local port such as 3000 and is never exposed to the internet directly.

What is the difference between pm2 restart and pm2 reload?

pm2 restart stops all processes of the app and starts them again, which causes a short interruption. pm2 reload replaces the processes one at a time in cluster mode, so there is always one that answers requests. In fork mode with a single process, reload behaves like restart.

How many instances should I run in cluster mode?

A good starting point is one instance per CPU core, which is what the max setting does. Each instance is a separate process with its own memory, so watch RAM usage and lower the number if the server starts swapping. The app must not keep sessions or other shared state in process memory.

Why does my site show a 502 Bad Gateway error?

Nginx couldn't reach the Node.js app. Either the app isn't running, it keeps crashing while starting, or it listens on a different port than the one in proxy_pass. Check pm2 status and pm2 logs first, then the Nginx error log in /var/log/nginx/error.log.

Nodesty

About the author

Nodesty Team · Infrastructure & Support

The Nodesty team runs our servers, network and DDoS protection day to day and answers customer support requests around the clock. These guides come from that work.

Related articles

Launch your server now.

Build, scale, and conquer without limits on Nodesty's premium infrastructure.

                                                                                                                                                                                                                            
                                                                                                                                                                                                                            
                                                                                                                                                                                                                            
                                                                                                                             ············································                                                   
                                                ··································································································..........···························                                     
                                       ················..........................................................................................................................··············                             
                                  ·············.................::::::::::::::::::::::::::::::::::::::::::::::....................:::::::::::::::::::::::::::::::::::::::................···········                        
                             ············................:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::............·········                     
                         ············.................:::::::::::::::::::::::::::::::::::::::::::::::::::------------::::::::::::::::::::::::::::::----------------:::::::::::::::::::::..........········                  
                    ············......................::::::::::::::::::::::::::::::::::::------------------------------------------------------------------------------------:::::::::::::.........········                
                ··········.............................................::::::::::::::::::-------------==========================================-----------------------------------:::::::::::........·······               
             ········..................:.....................................::::::::::--------=======+++++++++++++++++++++++++++++++++++++=========================------------------::::::::::.......·······              
           ······.........::::::::::::::::::::................................:::::::-----=====++++xxxxxx**************************xxxxxxxxx++++++++++++++===================------------::::::::.......·······             
          ·····.......:::::::::::::::::::::::::::.............................:::::----===+++xxx****%%%%&&&&&&#############&&&&&&&%%%%%*******xxxxxxxx++++++++++++++==============----------:::::::......······             
         ····......::::::::-------------:::::::::::..........................::::---===+++xx***%%%&&&####@@@@@@@@@@@@@@@@@@@@@@@@####&&&&&%%%%*******xxxxxxxxx+++++++++++++===========--------::::::......·····             
        ····.....:::::::--------------------:::::::::.......................::::---===++xxx**%%&&&###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###&&&&%%%%%********xxxxxxxxxxx++++++++++++========------::::::.....······            
        ····.....:::::--------------------------::::::::....................::::---===++xx***%%&&&####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###&&&&&%%%%%**********xxxxxxxxxxxxx+++++++++=======------:::::.....·····            
        ····....::::::-------=============---------:::::::::................:::::---===+++xx***%%%&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@#####&&&&&%%%%%%*************xxxxxxxxxxxxxx+++++++++======-----:::::....·····            
         ····....:::::-------================---------:::::::::...............:::::----===++++xxx***%%%%&&&&&&#################&&&&&&%%%%%%%*******************xxxxxxxxxxxxxxxxx++++++++======----:::::....·····            
         ·····....:::::--------=================---------::::::::::..............:::::::-----====+++++xxxxxx**************************xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx++++++++=====-----::::....·····            
          ·····.....:::::--------=================----------:::::::::::.................:::::::::-------=============++++++++++++++++++++++++++++++++++++xxxxxxxxxxxxxxxxxxxxxxx++++++++======-----::::....·····            
            ·····.....:::::::----------===========-------------::::::::::::.........................::::::::::::::::::------------------=============+++++++++++++++++++++++++++++++++=======-----::::.....·····            
              ······......:::::::---------------------------------:::::::::::::........................................:::::::::::::::-----------============+++++++++++++++++++++========------:::::.....·····             
                 ······........:::::::::---------------------------:::::::::::::::::...........................................:::::::::::::------------=============================--------::::::.....······              
                    ·········.........:::::::::::::::-------------::::::::::::::::::::::::.......................................::::::::::::::::--------------------------------------::::::::......·······                
                          ··········............::::::::::::::::::::::::::::::::::::::::::::::::::................................::::::::::::::::::::::::::-------------:::::::::::::::.........········                   
                                  ············..................:::::::::::::::::::::::::::::::::::::::::::.........................:::::::::::::::::::::::::::::::::::::................···········                        
                                             ················.............................................................................................................·················                                 
                                                           ······················................................................................···························                                                
                                                                               ·········································································