Sub topic 2
Private Subnets and NAT Gateways
Assume you know basic CIDR notation, TCP/UDP ports, AWS Regions, Availability Zones, and AWS CLI commands. A private subnet has no direct route to an internet gateway. Instances in it can still make outbound connections through a NAT gateway.
Private subnets and NAT gateways
Place the NAT gateway in a public subnet. Give the private subnet a default route to the NAT gateway. The NAT gateway replaces the private instance's source address with its public Elastic IP. Return traffic can reach the instance, but unsolicited internet traffic cannot start a connection to it.
# PRIVATE_RT_ID and NAT_ID were created earlier.
aws ec2 create-route \
--route-table-id "$PRIVATE_RT_ID" \
--destination-cidr-block 0.0.0.0/0 \
--nat-gateway-id "$NAT_ID"A NAT gateway is zonal. For production workloads, create one per Availability Zone and route each private subnet to the NAT gateway in the same zone. This improves resilience but increases cost.
Security groups: stateful instance-level firewalls
A security group is a stateful firewall attached to an elastic network interface. It has allow rules only. If an outbound request is allowed, its return traffic is automatically allowed.
Prefer references to other security groups over fixed IP ranges. For example, allow the database security group to accept PostgreSQL traffic only from the application security group.
| Control | Scope | Behavior |
|---|---|---|
| Security group | Network interface | Stateful, allow rules only |
| Network ACL | Subnet | Stateless, allow and deny rules |
Network ACLs: stateless subnet-level rules
A network access control list, or network ACL, filters traffic at the subnet boundary. It is stateless, so you must allow both directions explicitly. Return traffic commonly needs ephemeral client ports, such as TCP 1024–65535. Network ACLs are useful for broad subnet guardrails, but security groups are usually easier for application-specific access.
DNS resolution and hostnames inside a VPC
Enable DNS support and DNS hostnames on the VPC. These attributes let instances resolve AWS service names and receive internal DNS hostnames. Private DNS is important for service discovery and for interface VPC endpoints.
aws ec2 modify-vpc-attribute \
--vpc-id "$VPC_ID" \
--enable-dns-support "{\"Value\":true}"
aws ec2 modify-vpc-attribute \
--vpc-id "$VPC_ID" \
--enable-dns-hostnames "{\"Value\":true}"Exercise
An application in a private subnet needs outbound package updates but must not accept internet-initiated connections. What should its route table use?
Show answer
A default route to a NAT gateway in a public subnet. The instance's security group should also allow only the required traffic.