Internet & NAT Gateways
An internet gateway lets a public subnet talk to the internet; a NAT gateway lets private instances reach out without being reachable.
Gateways connect your VPC to the wider internet in two different ways.
Internet Gateway (IGW)
An internet gateway is attached to the VPC and allows two-way internet traffic for resources in public subnets that have a public IP. One IGW per VPC.
NAT Gateway
A NAT (Network Address Translation) gateway lets instances in a private subnet make outbound connections — to download updates or call an API — while blocking unsolicited inbound traffic. The NAT gateway itself lives in a public subnet.
Which to use
- Web servers that must accept inbound traffic → public subnet + IGW.
- App servers/databases that only need outbound → private subnet + NAT gateway.
Example
# Create and attach an internet gateway
aws ec2 create-internet-gateway
aws ec2 attach-internet-gateway \
--internet-gateway-id igw-0123456789abcdef0 \
--vpc-id vpc-0a1b2c3d4e5f67890
# Create a NAT gateway in a public subnet (needs an Elastic IP)
aws ec2 create-nat-gateway \
--subnet-id subnet-0a1b2c3d4e5f67890 \
--allocation-id eipalloc-0123456789abcdef0When to use it
- An internet gateway is attached to a VPC so that public-facing web servers can receive incoming connections from the internet.
- A NAT gateway in a public subnet allows private EC2 instances to download OS updates from the internet without exposing them to inbound connections.
- A company replaces a per-instance NAT instance with a managed NAT gateway to eliminate the single point of failure and manual maintenance.
More examples
Create and Attach Internet Gateway
Creates an internet gateway and attaches it to a VPC, enabling communication between VPC instances and the internet.
IGW=$(aws ec2 create-internet-gateway \
--query InternetGateway.InternetGatewayId --output text)
aws ec2 attach-internet-gateway \
--internet-gateway-id $IGW \
--vpc-id vpc-0abc123
echo "Internet Gateway $IGW attached"Create NAT Gateway in Public Subnet
Creates a managed NAT gateway with its own Elastic IP in a public subnet, allowing private instances to reach the internet.
# First allocate an Elastic IP
EIP=$(aws ec2 allocate-address --domain vpc --query AllocationId --output text)
# Create NAT gateway in the public subnet
aws ec2 create-nat-gateway \
--subnet-id subnet-public-0abc123 \
--allocation-id $EIP \
--query NatGateway.NatGatewayId \
--output textRoute Private Subnet Through NAT
Adds a default route pointing to the NAT gateway in the private subnet's route table, enabling outbound-only internet access.
# Add default route in the private subnet's route table to the NAT gateway
aws ec2 create-route \
--route-table-id rtb-private-0abc123 \
--destination-cidr-block 0.0.0.0/0 \
--nat-gateway-id nat-0abc1234def56789a
Discussion