NAT a VM port through its host interface

From Pabut
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 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
iptables -I FORWARD -d -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"

The second rule opens iptables to allow packets to

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