If you’re running multiple Node.js scripts under the same domain on a VPS like DigitalOcean, you’ll need to use a reverse proxy since two Node.js apps can’t listen on the same port. Nginx is a popular choice for setting up a reverse proxy.
To begin, you’ll need to edit the Nginx configuration file:
sudo nano /etc/nginx/sites-available/default
The default configuration file looks like this:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com;
location ^~ /assets/ {
gzip_static on;
expires 12h;
add_header Cache-Control public;
}
location / {
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
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_pass http://localhost:3000;
}
}
This configuration sets up a reverse proxy for a single Node.js app running on port 3000 and serving as the main app on the root path ("/").
If you want to run another app under the subfolder “/myservice”, you’ll need to create another Node.js app that listens on a different port (e.g., 3001) and add the following configuration:
location /myservice {
rewrite ^/myservice/(.*)$ /$1 break;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
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_pass http://localhost:3001;
}
After making these changes, it’s always a good idea to check the Nginx configuration for correctness:
sudo nginx -t
If everything looks fine, you can restart Nginx for the changes to take effect:
sudo systemctl restart nginx
Using Nginx as a reverse proxy allows you to serve multiple Node.js apps from subfolders under the same domain. Keep in mind that this setup assumes you have the necessary Node.js apps running on the specified ports (e.g., 3000 and 3001).