Web Development

How to Deploy a Node.js Backend on Ubuntu VPS Using PM2, Nginx, and SSL (2026 Guide)

Deploying a Node.js backend on an Ubuntu VPS allows you to host your API, manage application processes, connect custom domains, and configure HTTPS without…

D
DevByteTechnical Author
Published
12 min read11 views
How to Deploy a Node.js Backend on Ubuntu VPS Using PM2, Nginx, and SSL (2026 Guide)

Deploying a Node.js backend on an Ubuntu VPS allows you to host your API, manage application processes, connect custom domains, and configure HTTPS without relying on a platform-specific hosting service.

In this guide, we'll deploy a sample Node.js backend using PM2, configure Nginx as a reverse proxy, host multiple domains on the same VPS, and enable free SSL certificates using Let's Encrypt.

Every domain, IP address, username, and repository in this tutorial is fictional example data. Replace these values with your own when following the steps.

What You Will Need

Before starting, make sure you have:

  • An Ubuntu VPS with SSH access.

  • A Node.js backend project stored in Git.

  • A domain name that you control.

  • Access to your domain's DNS settings.

  • Basic knowledge of Linux terminal commands.

Example Environment

We'll use the following fictional setup throughout the tutorial.

Configuration

Example Value

Operating system

Ubuntu 24.04 LTS

Node.js version

22

VPS username

demo-user

Example VPS IP

203.0.113.10

Git repository

https://github.com/example-org/demo-api.git

Application directory

/home/demo-user/apps/demo-api

Node.js port

8001

Main domain

demo-example.com

API subdomain

api.demo-example.com

Second API subdomain

service.demo-example.com

Static website directory

/var/www/demo-site

The IP address is from a reserved documentation range, and the repository and domains are illustrative. They are not intended to identify a real deployment.

Step 1: Connect to the Ubuntu VPS

Open your terminal and connect to the server using SSH:

ssh demo-user@203.0.113.10

Here, demo-user is the example username, and 203.0.113.10 is the example server IP.

Replace them with the credentials provided by your VPS hosting provider.

Update the Ubuntu packages:

sudo apt update && sudo apt upgrade -y

This updates the package index and installs available system updates.

If the server requires a reboot after an important system update, schedule one when appropriate and reconnect after the server becomes available.

Step 2: Install Node.js and npm

Node.js runs your backend JavaScript code, while npm manages project dependencies.

Install the required packages:

sudo apt install -y ca-certificates curl gnupg

Configure the NodeSource repository for Node.js 22:

curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -

Install Node.js:

sudo apt install -y nodejs

Verify the installation:

node -v
npm -v

Both commands should display version numbers.

Node.js 22 is used for this example. For a new production deployment, choose a currently supported LTS release that is compatible with your application.

Step 3: Install Git and PM2

Git lets you download and update your source code. PM2 manages your Node.js application's lifecycle.

Install Git:

sudo apt install -y git

Install PM2 globally:

sudo npm install pm2@latest -g

Verify the installation:

pm2 -v

PM2 can restart an application after a crash and restore saved processes after a server reboot when its startup integration is configured correctly.

Step 4: Clone the Node.js Project

Create a directory for your applications:

mkdir -p ~/apps
cd ~/apps

Clone the fictional repository:

git clone https://github.com/example-org/demo-api.git

Enter the project directory:

cd demo-api

Install the dependencies:

npm install

If the project uses TypeScript or another build tool, run its build command:

npm run build

A build step is not necessary for every Node.js project. Check the scripts in your project's package.json.

Example package.json

A TypeScript backend might use scripts similar to these:

{
  "scripts": {
    "dev": "tsx watch src/server.ts",
    "build": "tsc",
    "start": "node dist/server.js"
  }
}

This example assumes the TypeScript compiler generates dist/server.js. Adjust the scripts to match your application's actual structure.

For a basic JavaScript Express backend, the start script might instead be:

{
  "scripts": {
    "start": "node server.js"
  }
}

Make sure your production start script works before proceeding.

Step 5: Configure Environment Variables

A Node.js application commonly needs environment variables for its port, database, authentication, and external services.

Create a production environment file in the project directory if your application uses one:

nano .env

Add example configuration:

NODE_ENV=production
PORT=8001
DATABASE_URL=replace_with_your_database_url
JWT_SECRET=replace_with_a_strong_random_secret

These values are placeholders. Replace them with the configuration required by your application.

Save the file and restrict its permissions:

chmod 600 .env

Make sure .env is included in .gitignore so production secrets are not committed to your repository.

Your application must load these environment variables. For example, an Express application using the dotenv package may contain:

import 'dotenv/config';

const PORT = process.env.PORT || 8001;

The example port is 8001. Your Nginx configuration and application configuration must use the same port.

Step 6: Start the Application with PM2

Once the dependencies and environment variables are configured, start the backend with PM2:

pm2 start npm --name "demo-api" -- run start

This tells PM2 to run the start script from package.json and register the process under the name demo-api.

Check the application status:

pm2 list

View the logs:

pm2 logs demo-api

To display the most recent 100 lines:

pm2 logs demo-api --lines 100

Press Ctrl + C to exit the log display.

Test the Backend Locally

Test the backend from the VPS:

curl http://127.0.0.1:8001

If the project has a health endpoint, test it directly:

curl http://127.0.0.1:8001/health

For example, the Express route could look like this:

app.get('/health', (req, res) => {
  res.status(200).json({
    success: true,
    message: 'Demo API is running'
  });
});

If the request succeeds, the application is responding locally. The domain and SSL configuration will be tested separately.

Step 7: Configure PM2 Startup

PM2 can manage your application during normal operation, but you should also configure it to restore the saved processes after a reboot.

Save the current process list:

pm2 save

Generate the startup configuration:

pm2 startup

PM2 will print a command that must be executed with sudo. Copy and run the exact command displayed by your server.

Then save the process list again:

pm2 save

Check the processes:

pm2 list

With startup integration enabled and the process list saved under the appropriate user, PM2 can restore your backend when the server boots.

Remember that this does not protect against every failure. A VPS outage, database failure, broken deployment, or server configuration issue can still prevent your application from working.

Step 8: Install Nginx

Nginx acts as a reverse proxy. It receives requests from your domain and forwards them to the Node.js application listening on port 8001.

Install Nginx:

sudo apt install -y nginx

Enable and start the service:

sudo systemctl enable --now nginx

Check its status:

sudo systemctl status nginx

If UFW is your firewall, you can allow SSH and web traffic using:

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw status

Only enable or modify the firewall after checking your existing rules and ensuring that you will not lose SSH access. Also check your VPS provider's network firewall.

Step 9: Configure Nginx for the API Domain

Suppose you want your backend to be accessible through:

api.demo-example.com

Create an Nginx configuration file:

sudo nano /etc/nginx/sites-available/demo-api

Add the following configuration:

server {
    listen 80;
    listen [::]:80;

    server_name api.demo-example.com;

    location / {
        proxy_pass http://127.0.0.1:8001;

        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 "upgrade";
    }
}

The proxy_pass directive forwards incoming requests to the Node.js application on port 8001.

The forwarding headers preserve useful information about the original request. The upgrade headers can support WebSocket connections, including those used by applications with Socket.IO.

Enable the configuration:

sudo ln -s /etc/nginx/sites-available/demo-api /etc/nginx/sites-enabled/demo-api

If the default Nginx site is no longer needed and conflicts with your setup, you can disable it:

sudo rm /etc/nginx/sites-enabled/default

Test the configuration:

sudo nginx -t

If the test succeeds, reload Nginx:

sudo systemctl reload nginx

Step 10: Configure DNS

Log in to the DNS provider for your domain and create an A record.

Type

Name

Value

A

api

Your actual VPS IPv4 address

This record points api.demo-example.com to your server once you replace the example domain and IP with values you control.

If you also want to use a root domain or a www hostname, configure their DNS records separately.

Do not add an AAAA record unless your VPS is configured to receive IPv6 traffic correctly.

After DNS has propagated, test the domain:

curl -I http://api.demo-example.com

A 502 Bad Gateway response usually means Nginx cannot connect to the backend. Check the PM2 status, application port, and Nginx error logs.

Step 11: Host Multiple Node.js Applications on One VPS

You can host multiple applications on a single VPS by assigning each application a different local port and configuring a separate Nginx server block for each domain.

For this example, we'll use:

Application

Domain

Port

Main application

demo-example.com

3000

First API

api.demo-example.com

8001

Second API

service.demo-example.com

8002

These applications must be configured to listen on their respective ports.

A. Configure the Main Application

Create a configuration file:

sudo nano /etc/nginx/sites-available/demo-main

Add:

server {
    listen 80;
    listen [::]:80;

    server_name demo-example.com www.demo-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;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

B. Configure the Second API

Create another configuration:

sudo nano /etc/nginx/sites-available/demo-service

Add:

server {
    listen 80;
    listen [::]:80;

    server_name service.demo-example.com;

    location / {
        proxy_pass http://127.0.0.1:8002;

        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 "upgrade";
    }
}

C. Enable the Configurations

Run:

sudo ln -s /etc/nginx/sites-available/demo-main /etc/nginx/sites-enabled/demo-main

sudo ln -s /etc/nginx/sites-available/demo-service /etc/nginx/sites-enabled/demo-service

Test and reload:

sudo nginx -t
sudo systemctl reload nginx

If a symbolic link already exists, inspect the existing configuration rather than creating a duplicate.

D. Start the Applications with PM2

For the main application:

cd ~/apps/demo-main
npm install
npm run build
pm2 start npm --name "demo-main" -- run start

For the second API:

cd ~/apps/demo-service
npm install
npm run build
pm2 start npm --name "demo-service" -- run start

These commands assume the example project directories exist and each project has a working production start script.

Configure each application to use its assigned port. For example, the second API could use:

PORT=8002

Save the PM2 process list:

pm2 save

Check the status of all applications:

pm2 list

Nginx routes requests to the correct application based on the incoming hostname. PM2 manages each application as a separate process.

Step 12: Host a Static HTML Website

Nginx can also host a static website without a Node.js process.

Suppose the website files are stored in:

/var/www/demo-site

The directory might contain:

/var/www/demo-site/
├── index.html
├── about.html
├── css/
│   └── style.css
├── js/
│   └── main.js
└── images/
    └── logo.png

Create the directory:

sudo mkdir -p /var/www/demo-site

Place your HTML, CSS, JavaScript, and image files in this directory, and ensure that Nginx has permission to read them.

Create the configuration:

sudo nano /etc/nginx/sites-available/demo-static

For a single-page application, use:

server {
    listen 80;
    listen [::]:80;

    server_name static.demo-example.com;

    root /var/www/demo-site;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Enable the configuration:

sudo ln -s /etc/nginx/sites-available/demo-static /etc/nginx/sites-enabled/demo-static

Validate and reload:

sudo nginx -t
sudo systemctl reload nginx

The try_files fallback is useful for a single-page application with client-side routing.

For a traditional multi-page HTML website, you can use:

location / {
    try_files $uri $uri/ =404;
}

Make sure static.demo-example.com points to the VPS in DNS. If you use the same domain for a static site and an API, configure path-based routing deliberately instead of creating competing server blocks.

Step 13: Install Free SSL with Let's Encrypt

SSL enables HTTPS and encrypts traffic between visitors and your server.

Before installing SSL, verify that the domain points to the correct VPS and that ports 80 and 443 are accessible.

Install Certbot and the Nginx plugin:

sudo apt update
sudo apt install -y certbot python3-certbot-nginx

For the first API domain:

sudo certbot --nginx -d api.demo-example.com

For the main domain and its www hostname:

sudo certbot --nginx -d demo-example.com -d www.demo-example.com

For the second API:

sudo certbot --nginx -d service.demo-example.com

Use these commands only after configuring the corresponding DNS records for domains you control. The example domains are placeholders, not working certificate targets.

Follow the prompts to complete validation and certificate installation. Certbot can update the Nginx configuration to enable HTTPS.

Test SSL Renewal

Let's Encrypt certificates are typically valid for 90 days. Certbot normally configures automated renewal on supported Ubuntu installations.

Test renewal:

sudo certbot renew --dry-run

Check the renewal timer:

systemctl list-timers | grep certbot

If the dry run fails, fix the underlying issue before relying on automatic renewal.

Step 14: Deploy New Code from Git

Once the backend is running, you'll need to update it whenever you push new changes to your repository.

Navigate to the project:

cd ~/apps/demo-api

Pull the latest code:

git pull

Install dependencies:

npm install

Build the project if necessary:

npm run build

Restart the correct PM2 process:

pm2 restart demo-api

Save the process list if you have changed which processes PM2 manages:

pm2 save

Check the logs:

pm2 logs demo-api --lines 100

For projects that commit a package-lock.json, you can use npm ci for reproducible installation in a deployment workflow:

cd ~/apps/demo-api
git pull
npm ci
npm run build
pm2 restart demo-api

This is a simple deployment example. Production deployments should also handle database migrations, application health checks, failed builds, and rollback procedures where appropriate.

Step 15: Useful PM2 Commands

Here are common commands for managing your deployed backend.

Command

Purpose

pm2 list

View all managed applications

pm2 logs demo-api

View application logs

pm2 restart demo-api

Restart the application

pm2 reload demo-api

Request a reload where supported

pm2 stop demo-api

Stop the application

pm2 delete demo-api

Remove the process from PM2

pm2 monit

Monitor application resource usage

pm2 save

Save the current process list

pm2 resurrect

Restore the saved process list

pm2 startup

Generate startup integration

Use the process name shown by pm2 list. Do not assume a process ID such as 0 will always refer to the same application.

Step 16: Troubleshoot Common Problems

Nginx Returns 502 Bad Gateway

Check PM2:

pm2 list
pm2 logs demo-api --lines 100

Test the backend directly:

curl http://127.0.0.1:8001

Confirm that Nginx uses the correct upstream port.

The Domain Does Not Open

Check Nginx:

sudo nginx -t
sudo systemctl status nginx

Verify DNS records, firewall rules, and the server's public IP address.

The Application Does Not Restart After a Reboot

Check the process list and startup configuration:

pm2 list
pm2 save
pm2 startup

Execute the startup command printed by PM2, then save the process list again.

Port Already in Use

An EADDRINUSE error means another process may already be using the configured port.

Inspect listening ports:

sudo ss -ltnp

Identify the process and resolve the port conflict without stopping unrelated services.

SSL Installation Fails

Verify that:

  • The domain points to the correct server.

  • DNS has propagated.

  • Ports 80 and 443 are reachable.

  • Nginx configuration passes sudo nginx -t.

  • The requested hostname is configured correctly.

Then retry Certbot after fixing the problem.

Check Nginx Error Logs

If the issue persists, inspect the error log:

sudo tail -n 100 /var/log/nginx/error.log

The log can help identify upstream connection failures, incorrect paths, and other Nginx issues.

Production Deployment Best Practices

Follow these recommendations to make your VPS deployment more reliable:

  1. Run applications as a dedicated non-root user.

  2. Protect environment files and keep secrets out of Git.

  3. Expose only the public ports your server needs.

  4. Bind backend ports to localhost when only Nginx needs access.

  5. Configure PM2 startup integration and test it after a planned reboot.

  6. Keep the operating system and application dependencies updated.

  7. Monitor logs, disk space, memory usage, and application health.

  8. Back up databases and other important data.

  9. Use a consistent deployment workflow with appropriate rollback options.

  10. Test certificate renewal rather than assuming it will always succeed.

Conclusion

Deploying a Node.js backend on an Ubuntu VPS becomes much easier when you understand the role of each component. Node.js runs your application, PM2 manages its process, Nginx routes traffic from your domains, and Let's Encrypt provides free SSL certificates.

Using the steps in this guide, you can deploy a Node.js or Express API, host multiple applications on one VPS, serve a static website, and update your backend from Git.

Start with a single application and domain, verify that the backend works locally, and then configure Nginx and HTTPS. Once the basic deployment works, you can extend the same setup to additional applications and automate future releases.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘