AWS allows developer to create an NAT instance in the public subnet, and provide private subnet the ability to access the internet.
Here is the precedure to create the NAT instance. For the iptables configuration, it's just a one line change.
In the EC2 console, disable source/dest checking by right clicking on the instance you want to use for NAT and choosing "Change Source / Dest Check".
Create a security group having an inbound rule allowing ALL from 10.0.0.0/16 and associate it with your NAT instance.
On the NAT instance, create /etc/network/if-pre-up.d/nat-setup as:
#!/bin/sh
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s 10.0.0.0/16 -j MASQUERADE
chmod +x the script, then run it. This script will automatically be run when the machine reboots, so your NAT will survive a restart.
Make sure all your private subnets have a default route to use the NAT instance as a gateway (create a route for 0.0.0.0/0 and associate it with your NAT instance in the route table(s) associated with your private subnets).
test your NAT by pinging something from an EC2 instance in a private subnet
Connections initiated from inside
If the connection is initiated from inside, I assume NAT instance works in this way.
EC2 Instance A (in private subnet) would like to access web server C in the internet.
EC2 instance A in private subnet send packets to NAT instance B.
NAT instance B forward the packets and do SNAT work, e.g.
- change the source ip in the packet.
- log this active connection to the conntrack tables.
Packets arrives to the server C in the internet.
Server C sends packets back to NAT instance B
Since the connection is in the conntrack tables
, all the packets are accept.
Connections initiated from Outside
If someone in the internet directly initiates a connection and send the packets to NAT instance, for example, ssh login, or ping.
what will NAT instance do?
How will the iptables of NAT instance handle the traffic based on the configuration in the preceding paragraph?
Reference
- Github gist: AWS NAT Instance creation
- Kabisa: Cost-saving with NAT instances
- AWS: NAT instances