How to add a subdomain for Nodejs application on DigitalOcean

When I was preparing this post I bought a domain just for testing purposes called nikola-dev.com and I wanted to have Node.js apps running on this VPS (behind a NGINX running as proxy) but that they would be accessible from different domains (for example mean.nikola-dev.com). Below are the steps I needed to take in order to make this happen:

  1. Clearly, have a droplet on DigitalOcean
  2. Buy a domain (where ever you buy it, make sure you use Honey, to get the best price)
  3. Edit the Nameserver information in the admin dashboard of your domain provider (where you bought the domain) to the following three records:
    ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com
  4. Add the domain on DigitalOcean DNS settings page:
    digitalOcean_dns
  5. Delete /etc/nginx/sites-enabled/default
  6. Create /etc/nginx/sites-available/nikola-dev.com file with the following content (this will be a simple single HTML file which will list the available test apps on this server):
    server {
        listen 80;
        server_name nikola-dev.com;
        root /var/www/nikola-dev.com/public_html;
    }
  7. Create /etc/nginx/sites-available/mean.nikola-dev.com file with the following content (this will serve the actual Node.js app that we’re building in this tutorial):
    server {
        listen 80;
    
        server_name mean.nikola-dev.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            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;
        }
    }
  8. Restart NGINX:
    sudo service nginx restart

Clearly, if you would need to add more subdomains, just repeat the steps from step onward. Of course, you would need to put your other Node.js apps on different ports, since only one app can work on one port.

Written by Nikola Brežnjak