devopsnginxnode.js

How I set up this subdomain in Nginx on Digital Ocean

Published at 2015-09-09

After hours of researching, I finally found a solution that worked for me.

My setup

I have a portfolio site and a blogging platform. Both are node.js apps, running on Express and Ghost. I run them on two ports; 8080 and 2368. I run a VM with Ubuntu 14.2 on Digital Ocean (5$/20GB SSD).

DNS on Digital Ocean

Nothing too fancy there. Create a DNS record in Digital Ocean. Set up an A record with the IP address and a CNAME that allows the "blog" subdomain.

$ORIGIN karlsolgard.net.
$TTL 1800
karlsolgard.net. 1800 IN NS ns1.digitalocean.com.
karlsolgard.net. 1800 IN NS ns2.digitalocean.com.
karlsolgard.net. 1800 IN NS ns3.digitalocean.com.
karlsolgard.net. 1800 IN A <YOUR IP HERE>
blog.karlsolgard.net. 1800 IN CNAME karlsolgard.net.

DNS registrations

Nginx on Ubuntu

I installed Nginx on the server by flipping up the terminal and running sudo apt-get install nginx. Nginx should be located at "/etc/nginx" in our file system. I deleted all files in the "/etc/nginx/sites-available" directory and created a file named "blogs". This is the files contents:

server {
  server_name blog.karlsolgard.net;
  
  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass       http://127.0.0.1:2368;
    }
}
 
server {
   server_name karlsolgard.net;
 
   location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass         http://127.0.0.1:8080;
    }  
}

Here we have a reverse proxy set up. In my solution, it's very important NOT to listen to port 80 on each server. Then it will resolve to the same port and it don't work. This is where I was stuck for a while.

After that, make a symbolic link to "sites-enabled" by running sudo ln -s /etc/nginx/sites-available/blogs /etc/nginx/sites-enabled/. Start the nginx server by running sudo service nginx start

Keeping node.js apps alive with PM2

I use the PM2 module, but you can also use forever. If you have node and npm installed, run npm i -g pm2 and find the directory of the app you want to run. Simply run NODE_ENV=production pm2 start 'serverfile'.js --name "YourName" . I did this for both node.js apps.

Results

Well, you are looking at it! Yaay! Took a bit longer than expected. I hope this post aids you with the same issues and brings you great relief. Check out my sites: blog and portfolio!

Avatar of Author

Karl SolgÄrd

Norwegian software developer. Eager to learn and to share knowledge. Sharing is caring! Follow on social: Twitter and LinkedIn.