I have a strange situation where I want to redirect a specific port on one host to another host. That is, traffic to 192.168.1.100:8080 => 192.168.1.101:8080.
Found the answer on LQ forums.
iptables -A PREROUTING -t nat -p tcp -d 192.168.1.100 --dport 8080 -j DNAT --to-destination 192.168.1.101 iptables -A POSTROUTING -t nat -p tcp -d 192.168.1.101 --dport 8080 -j SNAT --to-source 192.168.1.100
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.
- When a packet arrives at this computer, if protocol is TCP and destination is 192.168.1.100/32 (local IP) and destination port is 8080 then Destination NAT (change destination IP) to 192.168.1.101
- When a packet leaves this computer, if protocol is TCP and destination is 192.168.1.101/32 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 192.168.1.100. (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].
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.