How to create Virtual Hosts in node.Js and Ubuntu

Recently I needed to run multiple node.js application in my workspace which runs on ubuntu 12.04. It was not a issue, I just had to change the port numbers in the config.json file for each projects.
But I also wanted to run then under separate hosts which means virtual hosts. Using virtual host I could get rid of 127.0.0.1:3000 or localhost:3000 these kind of urls.

Configuration for node.js

The solution was simple ,I just added my virtual host name in the config file for the application. The configuration is like below.

"host": "nodeapp1.local",
"port" : "3000",
"url": "https://nodeapp1.local:3000",
"serverName": "nodeapp1.local"

Now your node.js app will be running under nodeapp1.local. But also you need tweak a little bit in your host file to make the virtual host working.

Configuration for Hosts file in ubuntu

In Ubuntu open your hosts file which should be located in the /etc folder. Also to edit the file you will be needed the admin permissions. You can open this file using any editor. Since it's simple line insertion, I'll to use nano.
Just run the follwing code in your terminal.

sudo nano /etc/hosts

This should open the hosts file in the terminal. It should be looking like the following template.

127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Now just add your virtual host under the locahost like the following code and save the file.

127.0.0.1 localhost
127.0.0.1 nodeapp1.local

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Save the file and your done. Now start your node.js application and hit https://nodeapp1.local:3000 in your browser to check if it's working or not :).

comments powered by Disqus