NAT a VM port through its host interface

From Pabut
Revision as of 17:38, 22 July 2015 by Pabut (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Sometimes you have VMs that are only connected to a virtual network on the host. Outbound connectivity, if any, is provided by NAT and iptables. That's fine, but what about internal connections to the VM? These two rules allow a HOST port to be NAT'ed to a VM port.

In this example, the VM has an internal network address of 192.168.122.244 and I want to be able to ssh to the VM directly from the outside. Since my HOST already has it's own SSH server on port 22, I choose to use 2200 for the VM.

iptables -t nat -A PREROUTING -p tcp --dport 2200 -j DNAT --to 192.168.122.244:22
iptables -I FORWARD -d 192.168.122.244/32 -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

So, the first rule says: "look for packets coming in for port 2200 and redirect them to 192.168.122.244:22"

The second rule opens iptables to allow packets to 192.168.122.244:22.

So now when I: "ssh -p 2200 HOSTNAME" I'm connected to the ssh server running on the VM.