
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 |
|
Example VPS IP |
|
Git repository |
|
Application directory |
|
Node.js port |
|
Main domain |
|
API subdomain |
|
Second API subdomain |
|
Static website directory |
|
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.10Here, 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 -yThis 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 gnupgConfigure 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 nodejsVerify the installation:
node -v
npm -vBoth 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 gitInstall PM2 globally:
sudo npm install pm2@latest -gVerify the installation:
pm2 -vPM2 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 ~/appsClone the fictional repository:
git clone https://github.com/example-org/demo-api.gitEnter the project directory:
cd demo-apiInstall the dependencies:
npm installIf the project uses TypeScript or another build tool, run its build command:
npm run buildA 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 .envAdd example configuration:
NODE_ENV=production
PORT=8001
DATABASE_URL=replace_with_your_database_url
JWT_SECRET=replace_with_a_strong_random_secretThese values are placeholders. Replace them with the configuration required by your application.
Save the file and restrict its permissions:
chmod 600 .envMake 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 startThis tells PM2 to run the start script from package.json and register the process under the name demo-api.
Check the application status:
pm2 listView the logs:
pm2 logs demo-apiTo display the most recent 100 lines:
pm2 logs demo-api --lines 100Press Ctrl + C to exit the log display.
Test the Backend Locally
Test the backend from the VPS:
curl http://127.0.0.1:8001If the project has a health endpoint, test it directly:
curl http://127.0.0.1:8001/healthFor 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 saveGenerate the startup configuration:
pm2 startupPM2 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 saveCheck the processes:
pm2 listWith 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 nginxEnable and start the service:
sudo systemctl enable --now nginxCheck its status:
sudo systemctl status nginxIf UFW is your firewall, you can allow SSH and web traffic using:
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw statusOnly 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-apiAdd 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-apiIf the default Nginx site is no longer needed and conflicts with your setup, you can disable it:
sudo rm /etc/nginx/sites-enabled/defaultTest the configuration:
sudo nginx -tIf the test succeeds, reload Nginx:
sudo systemctl reload nginxStep 10: Configure DNS
Log in to the DNS provider for your domain and create an A record.
Type | Name | Value |
|---|---|---|
A |
| 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.comA 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 |
|
|
First API |
|
|
Second API |
|
|
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-mainAdd:
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-serviceAdd:
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-serviceTest and reload:
sudo nginx -t
sudo systemctl reload nginxIf 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 startFor the second API:
cd ~/apps/demo-service
npm install
npm run build
pm2 start npm --name "demo-service" -- run startThese 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=8002Save the PM2 process list:
pm2 saveCheck the status of all applications:
pm2 listNginx 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.pngCreate the directory:
sudo mkdir -p /var/www/demo-sitePlace 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-staticFor 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-staticValidate and reload:
sudo nginx -t
sudo systemctl reload nginxThe 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-nginxFor the first API domain:
sudo certbot --nginx -d api.demo-example.comFor the main domain and its www hostname:
sudo certbot --nginx -d demo-example.com -d www.demo-example.comFor the second API:
sudo certbot --nginx -d service.demo-example.comUse 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-runCheck the renewal timer:
systemctl list-timers | grep certbotIf 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-apiPull the latest code:
git pullInstall dependencies:
npm installBuild the project if necessary:
npm run buildRestart the correct PM2 process:
pm2 restart demo-apiSave the process list if you have changed which processes PM2 manages:
pm2 saveCheck the logs:
pm2 logs demo-api --lines 100For 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-apiThis 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 |
|---|---|
| View all managed applications |
| View application logs |
| Restart the application |
| Request a reload where supported |
| Stop the application |
| Remove the process from PM2 |
| Monitor application resource usage |
| Save the current process list |
| Restore the saved process list |
| 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 100Test the backend directly:
curl http://127.0.0.1:8001Confirm that Nginx uses the correct upstream port.
The Domain Does Not Open
Check Nginx:
sudo nginx -t
sudo systemctl status nginxVerify 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 startupExecute 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 -ltnpIdentify 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.logThe 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:
Run applications as a dedicated non-root user.
Protect environment files and keep secrets out of Git.
Expose only the public ports your server needs.
Bind backend ports to localhost when only Nginx needs access.
Configure PM2 startup integration and test it after a planned reboot.
Keep the operating system and application dependencies updated.
Monitor logs, disk space, memory usage, and application health.
Back up databases and other important data.
Use a consistent deployment workflow with appropriate rollback options.
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.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


