Need correct iptable rules for NAT instance to prevent loop back for private subnet EC2 instance outgoing traffic

My AWS architecture has a public subnet having a NAT instance. It forwards the traffic on certain ports to my EC2 instance hosted in a separate private subnet.

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.1.126:80

But I also need to provide outgoing internet access to my private EC2 instances.

sudo iptables -t nat -A POSTROUTING -o eth0 -s 10.0.1.0/24 -j MASQUERADE

This results in all the request generated by my private EC2 instance to loop back to itself. Which rule needs to be modified to prevent this behaviour and outgoing traffic generated by private EC2 instance are sent without being routed back?

UPDATE: I added destination ip as my public ip for Port 80

sudo iptables -t nat -A PREROUTING -p tcp -d xx.xx.xx.xx --dport 80 -j DNAT --to-destination 10.0.1.126:80

Although my outgoing network call was not looped back but my dns based domain request are not getting passed to my instance.


Solution 1:

Your PREROUTING must exclude the local traffic, i.e.

iptables -t nat -A PREROUTING -p tcp ! --source 10.0.1.0/24 --dport 80 -j DNAT --to-destination 10.0.1.126:80

Note the exclamation mark before source: ! --source 10.0.1.0/24. That ensures that the rule is only evaluated for traffic coming from outside.

Hope that helps :)