Port Forwarding Small Port Numbers With Vagrant On OS X

While working with a Vagrant set-up it is easy to forward ports with the forwarded_port directive.

This is accomplished by making entries in the format below in your Vagrantfile:

config.vm.network :forwarded_port, guest: _guest_port_number, host: _host_port_number

The catch here is that Vagrant won’t forward ports when it comes to small port numbers on the host machine. This means that you will have to access the service on a higher port number, which is a bit of a downer considering the fact that we are going through all of this pain to have a development environment that is nearly an exact clone of what we will find on production.

The solution is to use ipfw (the humble IP Firewall in Unix-based and Linux systems), to forward the low port to a higher port and then forward that higher port to the corresponding low port on the VM.

Let us assume that you want to forward both HTTP (Port 80) and HTTPS (Port 443) to the Vagrant VM.

First, use ipfw to forward the ports with the host:

sudo ipfw add 100 fwd,8080 tcp from any to me 80

sudo ipfw add 101 fwd,8443 tcp from any to me 443

Then forward the lower ports to higher ones in the Vagrant file.

#forward httpd
config.vm.network :forwarded_port, guest: 80, host: 8080

#forward https
config.vm.network :forwarded_port, guest: 443, host: 8443

I do realize that this is a bit of a loopy way to go about accomplishing this, but when you have to juggle port numbers in a complex deployment environment, the overheads of keeping in mind the difference (and the set-up/code changes that will handle it) and the propensity to make mistakes will only keep increasing through time.

As far as I know, you can do the same with iptables on Linux, if ipfw is not your poison of choice, but I have not tested it.