Monday, August 19, 2013

Port forward from host to guest on Linux

It has been years since I have had to use iptables to modify routing on a Linux machine.

We are creating vm's using Vagrant and setting up applications using Chef.  In this case, the application we are setting up is the Thoughtworks Go server. 

The problem was that I was unable to access the Go server through the host and onto the VM.

I googled around and found a ton of information, and most didn't work, so here is another to add to the list :)

On your host machine, enter the following rules, replacing the guest IP address and port with your guests:
sudo iptables -t nat -A PREROUTING -p tcp --dport <port> -j DNAT --to
sudo iptables -A FORWARD -d -p tcp --dport 8153 -j ACCEPT
sudo iptables -A FORWARD -d -p tcp --dport 8153 -j ACCEPT
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
sudo sysctl net.ipv4.ip_forward=1

Now when I access my host with port 8153, it forwards the request over to the Go server, and all is fine.

To save and persist these rules, I installed the iptables-persistent package.  It saves out your rules into files located at /etc/iptables and adds the necessary scripts to load them on boot.

No comments:

Post a Comment