Lesson 11 / 33
NAT Gateways for Private Subnets
Give private instances outbound internet access with a NAT gateway and design it for availability.
By Rahul Agarwal · 15 years in web development
Outbound only, by design
Private application servers still need the internet: to download packages, call payment APIs or pull container images. A NAT gateway solves this. You place it in a public subnet (it needs an Elastic IP and a route to the IGW), then add 0.0.0.0/0 -> nat-... to the private subnets' route tables. When a private instance opens a connection, the NAT gateway rewrites the source to its own public address and tracks the connection so replies find their way back. Crucially, it does not accept connections that start on the internet, so private instances stay unreachable inbound. A managed NAT gateway is zonal: it lives in one AZ. If that AZ fails, every subnet routed through it loses egress, so the resilient pattern is one NAT gateway per AZ with each private subnet using the gateway in its own AZ. That also avoids cross-AZ data transfer charges. Google Cloud's equivalent is Cloud NAT, which is configured per region on a Cloud Router.
Egress path from a private subnet
Outbound traffic from a private server takes four hops: the private instance, the NAT gateway in a public subnet, the internet gateway, and finally the internet. Replies retrace the same path.
The college's outward-only phone line
Hostel rooms can dial out through the college switchboard, and the person they call sees the college's main number, not the room. But outsiders cannot dial a hostel room directly; the switchboard only connects calls that started inside.
NAT gateways cost money per hour and per GB
Heavy traffic to S3 or other provider services through a NAT gateway adds data-processing charges. Gateway or interface endpoints (covered later) keep that traffic off the NAT path.
Quick check: Where must an AWS NAT gateway for IPv4 internet egress be placed?
- In a public subnet with a route to an internet gateway
- In the private subnet it serves
- Outside the VPC, attached to the region
- On every EC2 instance as an agent
Answer
In a public subnet with a route to an internet gateway — A public NAT gateway sits in a public subnet so its own traffic can reach the internet gateway. Private subnets then route 0.0.0.0/0 to it.