October 06, 2014

MacOS and multiple (concurrent) Vagrant boxes

Are you running more than one Vagrant box concurrently, forcing you to resort to port numbers for correct working?

I am, and it's been annoying me for quite a while. Every of my sites has its own specific VirtualBox VM. Sometimes I might work on more than one at a given time (eg 2 sites communicating with each other via an API) so keeping them on the default ports and then only using 1 at a time wasn't a real solution.

So I decided to spend some time on the matter and see what I could trump up.
As it turns out... a lot!

Disclaimer: All information in here was assembled using related blog posts out there, I just turned it into a fairly usable script (check the last section for a link) :)

1. Different IP's

To be able to re-use port 80, which is a fairly important one in web-development </sarcasm>, you need multiple IPs. Turns out that you can actually add aliased IP's to an interface. I knew that was possible on a *nix machine, but it can be done apparently on a Mac as well:

sudo ifconfig lo0 alias

That's all there is to it.. So now you can ping the loopback interface with a seemingly public IP. The advantage? This is available even without internet connectivity!

Why that specific IP? 172.16/16 is a private range I don't use and 190 is 0xBE (for my company name, get it? :) )

2. Ports

Okay. So the next step would be to see if we can forward ports from that fake IP onto the regular localhost. 

Turns out Macs include ipfw, which is perfect, even though it is deprecated for pfctl.
So lets forward a port from the fake IP onto localhost:

ipfw add fwd,2001 tcp from me to dst-port 80

So basically I know have localhost:2001 listening for anything coming in on port 80 of our fake IP.

If anyone can help me do something similar with pfctl without having to "runtime-create" a bunch of config files, let me know and I'll update this post.

3. Hostname

Nearly there! All that remains is to give the IP a hostname and linking the ports to our VM.
The hostname part is easy, one line in /etc/hosts: myfirstvagrantbox.dev

4. Vagrantfile

In our vagrant configuration, we really don't care about all the IP stuff, we just need to know that port 2001 on localhost should bind to port 80 of our box:

config.vm.network :forwarded_port, :guest => 80, :host => 2001 

And there you have it! Reload the box and you can visit the webserver using the hostname, no ports involved.


So to make everything a bit easier I've thrown everything in a script that does all of that for you (except for the last step) and you can find that stuff in my vagrant github repository

If you checkout the README.md of the repository you might notice that I disable the redirect for port 2222, this is just to avoid errors when booting up multiple boxes that try to use that port.

Hope it helps.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.