How to host multiple Node.js applications with multiple different domains on one VPS with Nginx

First things first, if you bought your domain elsewhere then you first need to point that domain to your server. You basically have two options here

  • installing, setting up and running a DNS on your VPS and pointing the DNS (from the control panel where you bought a domain) records to your VPS
  • setting your DNS Zone file A record (in the control panel where you bought a domain) to the VPS IP
  • this posts explain what are the pros and cons

Now, if you do that for multiple domains they will all point to your server’s IP and show the same thing, essentially the thing which is running on port 80 (and that, in our main Nginx installation, will be a default Nginx welcome screen). If you have multiple Node.js applications, which are running on different ports, and you want to pinpoint the domains to that particular applications, then this is where the Nginx comes in so that it takes the requests for each domain and routes it to an appropriate port where the appropriate Node.js application is running. Basically, what Nginx does in this case is called reverse proxying.

Useful links:

Use forever:

  • npm install forever -g
  • forever start –spinSleepTime 10000 yourApp.js
  • if the app crashes, forever starts it up again

Lets start:

  • sudo vim /etc/nginx/conf.d/example.com.conf:
    server {
        listen 80;
    
        server_name your-domain.com;
    
        location / {
            proxy_pass http://localhost:{YOUR_PORT};
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
  • to reference multiple domains for one Node.js app (like www.example.com and example.com) you need to add the following code to the file /etc/nginx/nginx.conf in the http section: server_names_hash_bucket_size 64;
  • but, as it always is, the upper statement didn’t work for me, so I ended up using this solution from StackOverflow:
    server {
        #listen 80 is default
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
    }
  • sudo service nginx restart

Forever keeps your application running when it crashes but if VPS is rebooted it won’t start anymore. Simple cronjob solves this issue. Create starter.sh in your application’s home folder and copy the following code:

#!/bin/sh

if [ $(ps -e -o uid,cmd | grep $UID | grep node | grep -v grep | wc -l | tr -s "\n") -eq 0 ]
then
export PATH=/usr/local/bin:$PATH
forever start --sourceDir /path/to/your/node/app main.js >> /path/to/log.txt 2>&1
fi

where main.js is your application’s main script. Add to crontab the following line: @reboot /path/to/starter.sh.

Written by Nikola Brežnjak