Redirecting a port to another host on same LAN using iptables

By , 2010-11-27 22:53

I have a strange situation where I want to redirect a specific port on one host to another host. That is, traffic to =>

Found the answer on LQ forums.

iptables -A PREROUTING -t nat -p tcp -d --dport 8080 -j DNAT --to-destination
iptables -A POSTROUTING -t nat -p tcp -d --dport 8080 -j SNAT --to-source

Don’t ask me why this works. It just does. Well, the first line makes sense, but I have no idea what the second is doing.

After looking at the rule in Webmin, I think I figured it out.

  1. When a packet arrives at this computer, if protocol is TCP and destination is (local IP) and destination port is 8080 then Destination NAT (change destination IP) to
  2. When a packet leaves this computer, if protocol is TCP and destination is and destination port is 8080 (as would be the case for any packet modified by the above rule), then Source NAT (change source IP) to (This ensures that the remote host .101 returns any packets via this computer, .100, rather than simply attempting to send them to the original requesting host.)

Update: This even works on an OpenVZ container! Just need to enable iptables nat in the vz config on the hardware node (VM host) [source].

nano /etc/vz/vz.conf

Then do Control W and SEARCH for IPTABLES

Comment out (by adding a # symbol to the line ) the current IPTABLES= line

and then copy/paste and add this line directly underneath the line you just commented out.

IPTABLES="ipt_REJECT ipt_recent ipt_owner ipt_REDIRECT ipt_tos ipt_TOS ipt_LOG ip_conntrack ipt_limit ipt_multiport iptable_filter iptable_mangle ipt_TCPMSS ipt_tcpmss ipt_ttl ipt_length ipt_state iptable_nat ip_nat_ftp"

It is important to make sure this is all in 1 line and that it does not wrap.

Now Control-S and save – overwriting the current file.

Finally do an /etc/init.d/vz restart
to restart openVZ.

Leave a Reply


Custom theme by me. Based on Panorama by Themocracy