Iptables MASQUERADE only selected ports
Solution 1:
if you really want to do a MASQUERADE
then the proper way to do this is like this:
iptables -t nat -A PREROUTING -p tcp --dport 1111 -j DNAT --to-destination 2.2.2.2:1111
iptables -t nat -A POSTROUTING -d 2.2.2.2 -p tcp --dport 1111 -j MASQUERADE
this way MASQUERADE
will be applied only to DNAT-ed packets.
Note however that MASQUERADE
is intended mostly for dynamic IP cases (such as dial-up) and in case of a static IP SNAT
should rather be used just the way you proposed. From iptables
man page:
It should only be used with dynamically assigned IP (dialup) connections: if you have a static IP address, you should use the SNAT target. Masquerading is equivalent to specifying a mapping to the IP address of the interface the packet is going out, but also has the effect that connections are forgotten when the interface goes down. This is the correct behavior when the next dialup is unlikely to have the same interface address (and hence any established connections are lost anyway).
there is 1 caveat though for both MASQUERADE
and SNAT
: it won't work if 2.2.2.2 is a VIP on the same machine.