Skip to main content

Designing a Production VPC with NAT and Subnets

Design a production VPC with public and private subnets, Internet Gateway, NAT Gateway, Security Groups, endpoints, and Flow Logs, step by step.

Overview and What You Will Learn

A VPC (Virtual Private Cloud) is your own isolated network inside AWS, and almost every resource you launch, such as EC2, RDS and ECS, lives in one. In this lab you design a two-AZ VPC with public and private subnets, an Internet Gateway, one NAT Gateway per AZ, a free S3 Gateway Endpoint and VPC Flow Logs, all from the AWS CLI.

By the end you will be able to:

  • Plan CIDR blocks and subnets, including the 5 addresses AWS reserves in every subnet
  • Explain exactly what makes a subnet public or private
  • Reach private instances with a bastion host or Session Manager
  • Give private instances outbound internet access with NAT Gateways
  • Compare Security Groups and NACLs, and avoid the ephemeral port trap
  • Use VPC Endpoints to cut NAT costs and keep traffic on the AWS network
  • Debug connectivity with VPC Flow Logs and connect VPCs with peering

Why This Matters in Production

Get the VPC wrong and you either expose a database to the internet or lock things down so tightly that your application cannot reach what it needs. Both are costly, and every later networking problem traces back to this layer.

Typical incidents are quiet ones. A NACL change can silently drop a share of API traffic, and Flow Logs show the REJECT records that point to the cause in minutes. A team that sends heavy S3 traffic through a NAT Gateway pays per GB for traffic that never needed the internet, when a free S3 Gateway Endpoint would remove that cost.

Core Principles

What Is a VPC and How Do CIDR Blocks Work?

A VPC is a private network defined by a CIDR block, the pool of IP addresses all its subnets share. AWS recommends private RFC 1918 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. A VPC CIDR can range from /16 to /28, and a common production choice is 10.0.0.0/16 with 65,536 addresses. Every account also has a default VPC in each Region, which is fine for experiments but not for production.

Remember

Plan CIDR ranges before you build. Peering and VPN connections need non-overlapping ranges, and fixing an overlap later means rebuilding.

How Do Subnets and the 5 Reserved IP Addresses Work?

A subnet is a slice of the VPC CIDR block that lives in exactly one Availability Zone, and instances launch into subnets, not directly into the VPC. In every subnet AWS reserves five addresses, so a /24 with 256 addresses has 251 usable.

Address in 10.0.1.0/24 Reserved for
10.0.1.0 Network address
10.0.1.1 VPC router
10.0.1.2 AWS DNS
10.0.1.3 Future use
10.0.1.255 Broadcast address

A subnet cannot be resized after creation, so size generously. A /27 gives only 27 usable addresses, while a /26 gives 59. Load balancers, Lambda in a VPC and container networking also consume addresses.

TEXT
VPC 10.0.0.0/16
public-1a 10.0.1.0/24 ap-south-1a
public-1b 10.0.2.0/24 ap-south-1b
private-1a 10.0.10.0/24 ap-south-1a
private-1b 10.0.11.0/24 ap-south-1b
What Makes a Subnet Public or Private?

A subnet is public when its route table sends internet traffic to an Internet Gateway and its instances have a public IP. All three conditions must be true: an Internet Gateway is attached to the VPC, the subnet route table has 0.0.0.0/0 pointing to that gateway, and the instance has a public or Elastic IP. If any one is missing, the subnet is effectively private.

flowchart TD A([Internet]) --> B[Internet Gateway] B --> C[Public subnet: ALB, NAT, bastion] C --> D[NAT Gateway] D --> E[Private subnet: app, RDS] classDef net fill:#8B5CF6,color:#ffffff classDef pub fill:#F97316,color:#ffffff classDef priv fill:#10B981,color:#ffffff class A net class B,C,D pub class E priv
  • Public subnets hold load balancers, NAT Gateways and bastion hosts
  • Private subnets hold app servers, databases and caches
  • Public IPv4 addresses are billed per hour, so avoid giving them to instances that do not need them
Common Mistake

Attaching an Internet Gateway but forgetting the 0.0.0.0/0 route to it in the route table. The gateway exists but nothing uses it. Always check route tables first when debugging connectivity.

How Do You Reach Private Instances: Bastion Host or Session Manager?

A bastion host is a small instance in a public subnet used as the single SSH entry point to private instances. Lock its security group to your own IP on port 22, and allow SSH on the private instance only from the bastion's security group ID. Session Manager and EC2 Instance Connect Endpoint are modern alternatives that need no public IP and no open port 22, and they are usually the better choice.

Security

Never open port 22 to 0.0.0.0/0 on any security group. Scanners find new public IPs within minutes.

What Is a NAT Gateway and How Does It Work?

A NAT Gateway lets instances in private subnets start outbound connections to the internet while staying unreachable from it. It lives in a public subnet and uses an Elastic IP. Private traffic goes to the NAT Gateway, which swaps the source address for its own public one, sends the request out, and returns the reply to the private instance.

Property Value
Location Public subnet
Needs An Elastic IP
Management Fully managed by AWS
Scaling Automatic, up to 100 Gbps
Billing Per hour plus per GB processed

Create one NAT Gateway per AZ and route each private subnet to the one in its own AZ. This avoids cross-AZ data charges and means one AZ failing does not remove internet access for the others. Check the current docs for the newer regional NAT Gateway option before choosing a layout.

Common Mistake

Using a single NAT Gateway for the whole VPC. If its AZ fails, every private instance in other AZs loses internet access.

What Is the Difference Between Security Groups and NACLs?

Security Groups are stateful firewalls on resources that only allow traffic, and NACLs are stateless firewalls on subnets that allow and deny. Stateful means return traffic for an allowed connection is allowed automatically. Stateless means each direction is checked on its own, so a NACL needs an outbound rule for the response too.

Security Group NACL
Attached to Resource (ENI) Subnet
Rules Allow only Allow and deny
State Stateful Stateless
Block one IP No Yes

NACL rules are evaluated from the lowest number up and the first match wins. A custom NACL denies everything until you add rules, and responses to clients return on ephemeral ports (1024-65535 is a safe range), so outbound rules must allow them.

Chain security groups by referencing group IDs, not IP addresses, because IPs change and group IDs do not:

◈ DIAGRAM
Internet -> ALB SG: allow 80 and 443 from 0.0.0.0/0
ALB SG -> App SG: allow 8080 from the ALB SG
App SG -> DB SG: allow 5432 from the App SG
Remember

Use Security Groups as the main control. Use NACLs as a second layer, mainly to block a specific IP address.

What Are VPC Endpoints and When Should You Use Them?

A VPC Endpoint gives private instances a path to AWS services that stays on the AWS network and avoids NAT charges. Gateway Endpoints work for S3 and DynamoDB, are free, and work by adding a route to your route tables. Interface Endpoints use AWS PrivateLink to put a private IP in your subnet for most other services, and they cost per hour and per GB.

Gateway Endpoint Interface Endpoint
Services S3, DynamoDB Most other services
Cost Free Hourly plus per GB
Mechanism Route table entry Private IP in subnet
Tip

Create S3 and DynamoDB Gateway Endpoints in every VPC from day one. They are free and remove NAT processing fees for that traffic.

How Do VPC Flow Logs Help You Debug Network Problems?

Flow Logs record IP traffic flows on a VPC, subnet or network interface, with the source, destination, ports and an ACCEPT or REJECT action. Records are aggregated over a short window, so they are not packet captures, and some traffic such as the Amazon DNS server, DHCP and instance metadata is not logged. Send logs to CloudWatch Logs for alerts or to S3 for archiving and Athena queries.

  • REJECT on inbound traffic points to a Security Group or NACL blocking the request
  • ACCEPT inbound with REJECT on the reply often points to a NACL missing the ephemeral port rule
Tip

A timeout means something dropped the packet, so check Security Groups and NACLs. Connection refused means the packet arrived but nothing listens on that port, so check the application.

What Is a NAT Instance and Why Does Source/Destination Check Matter?

A NAT instance is the legacy approach where you run your own EC2 instance as the NAT device, and it must have Source/Destination Check disabled. By default an instance drops packets not addressed to itself, which would silently drop all the traffic a NAT instance is supposed to forward. NAT Gateway handles this for you and is the right choice for new designs.

NAT Gateway NAT Instance
Management AWS You
Availability Built in per AZ Your setup
Source/dest check Not applicable Must disable
How Does VPC Peering Work?

VPC Peering creates a private connection between two VPCs over the AWS network, in the same or different accounts or Regions. Peering is not transitive, so if A peers with B and B peers with C, A still cannot reach C. The two VPCs cannot have overlapping CIDRs, and you must add routes and security group rules on both sides. For many VPCs, Transit Gateway is easier than a mesh of peerings.

Which VPC Networking Costs Should You Watch?

Traffic inside the same AZ over private IPs is free and inbound internet traffic is free, while cross-AZ traffic, outbound internet traffic and NAT Gateway processing are billed. Prices vary by Region, so check current pricing.

  • Cross-AZ traffic is billed per GB in each direction, so keep chatty tiers such as app and database traffic in the same AZ where you can
  • NAT Gateway charges per GB processed, so route S3 and DynamoDB through Gateway Endpoints
  • Public IPv4 addresses are billed hourly

Detailed Step-by-Step Practical Lab

This lab builds the VPC with the AWS CLI in ap-south-1. NAT Gateways and Elastic IPs cost money while they run, so clean up as soon as you finish.

Step 1: Create the VPC
Bash
export AWS_REGION=ap-south-1
VPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 \
--query 'Vpc.VpcId' --output text)
aws ec2 create-tags --resources $VPC_ID --tags Key=Name,Value=devops-prod-vpc
aws ec2 modify-vpc-attribute --vpc-id $VPC_ID --enable-dns-hostnames
Step 2: Create four subnets
Bash
PUB_A=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.1.0/24 \
--availability-zone ap-south-1a --query 'Subnet.SubnetId' --output text)
PUB_B=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.2.0/24 \
--availability-zone ap-south-1b --query 'Subnet.SubnetId' --output text)
PRIV_A=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.10.0/24 \
--availability-zone ap-south-1a --query 'Subnet.SubnetId' --output text)
PRIV_B=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.11.0/24 \
--availability-zone ap-south-1b --query 'Subnet.SubnetId' --output text)
aws ec2 create-tags --resources $PUB_A --tags Key=Name,Value=public-1a
aws ec2 create-tags --resources $PUB_B --tags Key=Name,Value=public-1b
aws ec2 create-tags --resources $PRIV_A --tags Key=Name,Value=private-1a
aws ec2 create-tags --resources $PRIV_B --tags Key=Name,Value=private-1b
aws ec2 modify-subnet-attribute --subnet-id $PUB_A --map-public-ip-on-launch
aws ec2 modify-subnet-attribute --subnet-id $PUB_B --map-public-ip-on-launch
Step 3: Create and attach the Internet Gateway
Bash
IGW_ID=$(aws ec2 create-internet-gateway \
--query 'InternetGateway.InternetGatewayId' --output text)
aws ec2 attach-internet-gateway --internet-gateway-id $IGW_ID --vpc-id $VPC_ID
Step 4: Create the public route table
Bash
PUB_RT=$(aws ec2 create-route-table --vpc-id $VPC_ID \
--query 'RouteTable.RouteTableId' --output text)
aws ec2 create-route --route-table-id $PUB_RT \
--destination-cidr-block 0.0.0.0/0 --gateway-id $IGW_ID
aws ec2 associate-route-table --route-table-id $PUB_RT --subnet-id $PUB_A
aws ec2 associate-route-table --route-table-id $PUB_RT --subnet-id $PUB_B
Step 5: Create one NAT Gateway per AZ
Bash
EIP_A=$(aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text)
EIP_B=$(aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text)
NAT_A=$(aws ec2 create-nat-gateway --subnet-id $PUB_A --allocation-id $EIP_A \
--query 'NatGateway.NatGatewayId' --output text)
NAT_B=$(aws ec2 create-nat-gateway --subnet-id $PUB_B --allocation-id $EIP_B \
--query 'NatGateway.NatGatewayId' --output text)
# Wait until both are available (1 to 2 minutes)
aws ec2 wait nat-gateway-available --nat-gateway-ids $NAT_A $NAT_B
Step 6: Create the private route tables
Bash
PRIV_RT_A=$(aws ec2 create-route-table --vpc-id $VPC_ID \
--query 'RouteTable.RouteTableId' --output text)
aws ec2 create-route --route-table-id $PRIV_RT_A \
--destination-cidr-block 0.0.0.0/0 --nat-gateway-id $NAT_A
aws ec2 associate-route-table --route-table-id $PRIV_RT_A --subnet-id $PRIV_A
PRIV_RT_B=$(aws ec2 create-route-table --vpc-id $VPC_ID \
--query 'RouteTable.RouteTableId' --output text)
aws ec2 create-route --route-table-id $PRIV_RT_B \
--destination-cidr-block 0.0.0.0/0 --nat-gateway-id $NAT_B
aws ec2 associate-route-table --route-table-id $PRIV_RT_B --subnet-id $PRIV_B
Step 7: Add the free S3 Gateway Endpoint
Bash
aws ec2 create-vpc-endpoint \
--vpc-id $VPC_ID \
--vpc-endpoint-type Gateway \
--service-name com.amazonaws.ap-south-1.s3 \
--route-table-ids $PRIV_RT_A $PRIV_RT_B

S3 traffic from the private subnets now uses the endpoint route instead of the NAT Gateway.

Step 8: Enable VPC Flow Logs to S3
Bash
aws s3 mb s3://devops-vpc-flowlogs-rahul --region ap-south-1
aws ec2 create-flow-logs \
--resource-type VPC \
--resource-ids $VPC_ID \
--traffic-type ALL \
--log-destination-type s3 \
--log-destination arn:aws:s3:::devops-vpc-flowlogs-rahul
Step 9: Verify the routes
Bash
aws ec2 describe-route-tables --route-table-ids $PUB_RT $PRIV_RT_A \
--query 'RouteTables[].Routes[].[DestinationCidrBlock,GatewayId,NatGatewayId]' \
--output table

The public table should show 0.0.0.0/0 to the Internet Gateway, and the private table should show 0.0.0.0/0 to a NAT Gateway plus the S3 endpoint route.

Step 10: Clean up in order
Bash
aws ec2 delete-nat-gateway --nat-gateway-id $NAT_A
aws ec2 delete-nat-gateway --nat-gateway-id $NAT_B
aws ec2 wait nat-gateway-deleted --nat-gateway-ids $NAT_A $NAT_B
aws ec2 release-address --allocation-id $EIP_A
aws ec2 release-address --allocation-id $EIP_B
# Delete the endpoint and flow log using their IDs from describe-vpc-endpoints and describe-flow-logs
aws ec2 detach-internet-gateway --internet-gateway-id $IGW_ID --vpc-id $VPC_ID
aws ec2 delete-internet-gateway --internet-gateway-id $IGW_ID
for S in $PUB_A $PUB_B $PRIV_A $PRIV_B; do aws ec2 delete-subnet --subnet-id $S; done
for R in $PUB_RT $PRIV_RT_A $PRIV_RT_B; do aws ec2 delete-route-table --route-table-id $R; done
aws ec2 delete-vpc --vpc-id $VPC_ID

Production Best Practices & Common Pitfalls

  • Keep apps and databases in private subnets: Only load balancers, NAT Gateways and bastions belong in public subnets.
  • One NAT Gateway per AZ: It costs more than one, and an outage costs more still.
  • Create S3 and DynamoDB Gateway Endpoints first: They are free and cut NAT charges.
  • Reference security groups, not IPs: Group IDs survive instance restarts.
  • Prefer Session Manager over bastions: It removes open SSH ports entirely.
  • Allow ephemeral ports in NACLs: Stateless rules need both directions.
  • Plan CIDRs up front: Non-overlapping ranges keep peering and VPN options open.
  • Turn on Flow Logs early: You cannot see past traffic you never recorded.
  • Size subnets generously: They cannot be resized later.
Common Mistake

Placing app servers or databases in a public subnet. They become reachable from the internet, and they belong in private subnets behind a load balancer.

Common Mistake

Sending S3 traffic through a NAT Gateway. It is billed per GB, and the S3 Gateway Endpoint is free.

Quick Reference & Troubleshooting Commands

Task Command
List VPCs aws ec2 describe-vpcs
List subnets aws ec2 describe-subnets --filters Name=vpc-id,Values=<VPC-ID>
Show route tables aws ec2 describe-route-tables --filters Name=vpc-id,Values=<VPC-ID>
List NAT Gateways aws ec2 describe-nat-gateways
List endpoints aws ec2 describe-vpc-endpoints
List flow logs aws ec2 describe-flow-logs
Inspect a security group aws ec2 describe-security-groups --group-ids <SG-ID>
Problem Likely cause and fix
Public instance has no internet Missing 0.0.0.0/0 route to the Internet Gateway, or no public IP.
Private instance cannot reach the internet No route to a NAT Gateway, or NAT Gateway in a private subnet.
Connection timeout Security Group or NACL blocking. Check Flow Logs for REJECT.
Connection refused App not listening on that port. Security rules are fine.
Replies blocked NACL missing outbound ephemeral port rule.
Peering ping fails Missing routes or security group rules on one side, or overlapping CIDRs.
High NAT bill S3 or DynamoDB traffic going through NAT. Add Gateway Endpoints.

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Networking and Security

All 6 Topics

Frequently Asked Questions

Is Designing a Production VPC with NAT and Subnets free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Designing a Production VPC with NAT and Subnets topic cover?

Design a production VPC with public and private subnets, Internet Gateway, NAT Gateway, Security Groups, endpoints, and Flow Logs, step by step.

Found a mistake, an outdated step or a broken link?