24

I am trying to run multiple Node.js web servers locally on my machine.

Because the code I'm writing needs to reference a domain name I'd like to keep a convention of dev.myHost.com and point that to the non-port-80 service running from Node (technically I'm running one on Harp.js and one on Sails.js).

  • So dev.hostOne.com should point to localhost:123
  • and dev.hostTwo.com should point to localhost:456

Is this possible? If so, how.

krisFR
  • 12,830
  • 3
  • 31
  • 40
mondo
  • 383
  • 1
  • 2
  • 4

1 Answers1

31

From my understanding, it seems that you only use one local dev machine, means not connected to any network that provides a DNS.

If i am right, i would suggest to setup things like described below :

step 1 : Assign at least two IP address to your MAC OS (one per domain), let's say :

192.168.0.10
192.168.0.11

To setup the second IP you will have to add a second Ethernet Adapter (logical not physical).

Step 2 : As you don't have a DNS server, you could setup your /etc/hosts file, by adding :

192.168.0.10     dev.hostone.com
192.168.0.11     dev.hosttwo.com

Step 3 : Assign aliases to your loopback interface :

sudo ifconfig lo0 192.168.0.10 alias
sudo ifconfig lo0 192.168.0.11 alias

Step 4 : Setup ipfw to forward packets :

sudo ipfw add fwd 127.0.0.1,123 tcp from me to 192.168.0.10 dst-port 80
sudo ipfw add fwd 127.0.0.1,456 tcp from me to 192.168.0.11 dst-port 80

You are done !

Now :

enter image description here enter image description here


I've setup two Node.js web servers to test your case :

$ netstat -anp tcp | grep -E "123|456"
tcp4    0    0  127.0.0.1:123    *.*    LISTEN
tcp4    0    0  127.0.0.1:456    *.*    LISTEN

Important : note that ipfw rules and loopback interface aliases are not persistent and will no longer exist after a reboot. So consider adding a startup script.

krisFR
  • 12,830
  • 3
  • 31
  • 40
  • 2
    Worked BEAUTIFULLY. This is EXACTLY what I wanted. – mondo Feb 10 '14 at 15:19
  • 1
    Glad it works ! i was pretty sure that it was not totally a "duplicate" ;) – krisFR Feb 10 '14 at 15:26
  • on Mac os sierra getting sudo: ipfw: command not found – ClintM Mar 20 '17 at 00:47
  • 5
    @ClintM: `ipfw` has been replaced by `pfctl`. For an example of how to open a port: https://gauravsohoni.wordpress.com/2015/04/14/mac-osx-open-port/ – Joe Atzberger Apr 25 '17 at 20:04
  • 4
    It would be really nice to update the answer in the pfctl expected format. – Simon Jul 20 '17 at 05:54
  • If ipfw is not available. You have do this https://gist.github.com/allexradu/52f88344f207960621d5f086fcaf4b69 – Allex Radu Aug 22 '21 at 19:27
  • Instead of all those steps, you can assign different domains to localhost (127.0.0.1) in `/etc/hosts`, then install a web server (e.g. Nginx) and configure port forwarding in it: https://serverfault.com/questions/536576/nginx-how-do-i-forward-an-http-request-to-another-port – Adrian Bienias Dec 17 '21 at 08:02