Port forwarding on your Mac for easier development


Why Port forward?

When doing development for this site I wanted to have a local setup that would run Ghost. This could be done with vagrant and some other goodies, but for the sake of time I just wanted to run ghost and deploy to production.

Typically, the way we do this is to use vagrat, XAMPP, or an equivilant server setup, make an entry in your computers host file, then configure a vhost on apache or nginx to point to the url we want, in this case imperativedesign.net.

When you run ghost though, it doesn's serve requests on port 80 my dev setup serves them on port 2368. That means you can't just add an entry in your host file, and go to imperativedesign.net and be working locally.

To jump this hurdle we can either suffix the url with :2368 ( which looks ugly ) or we can point port 80 to port 2368. I like the latter approach.

Making it happen

In the past, I used to use the *nix utility ipfw but in Yosemite it was deprecated. So that leaves us with port forwading with anchors.

Step 1: Create a forwarding rule

The first step is to create a file that contains forwarding rules.

#sudo vim /etc/pf.anchors/dev.forwarding
rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 2368  

`

Step2: Create a port forwarding config file
#sudo vim /etc/pf-dev.conf
rdr-anchor "forwarding"  
load anchor "forwarding" from "/etc/pf.anchors/eclipse.tomcat.forwarding"

#Note: ^^^ you need an emptly newline at the bottom of the file or it wont work.     
Step 3: Apply the rule
sudo pfctl -ef /etc/pf-dev.conf  
Step 4: Lastly enter a rule in your host file

This last step ensures all requests to 127.0.0.1 aka localhost go to your mapped port.

#sudo vim /etc/host
//....Stuff above
127.0.0.1    imperativedesign.net  

Voila, now anytime I try to go to imperativedesign.net it redirects to my local development environment running on port 2368. You can use this same technique to map local php instances running on something like Nginx and port 8080 or anything else you can think of.

Turning it off when your'e done

The last step is just to turn it off when you finish so requests go to the right place. This is simple, just type:

sudo pfctl -d

sudo pfctl -F all -f /etc/pf.conf  

The first command flushes our custom config rules.
The next command reload's the default mac port configs.

Sources:

http://abetobing.com/blog/port-forwarding-mac-os-yosemite-81.html
https://gist.github.com/zhoutong/8adca7038639f0f5fb0e