AWS VPC Step by Step - Create a VPC with Public and Private Subnets, Internet Gateway, NAT Gateway and Route Tables (and Test It with EC2) (AWS Part-5)


In Part-4 I launched an EC2 instance into the default VPC and did not think about the network at all. That is fine for a lab and wrong for everything else - a database with a public IP address is how companies end up in the news. In this Part-5 we build the network that every real AWS workload sits in: a VPC (Virtual Private Cloud) with public subnets for the things the internet may reach (load balancers, a bastion) and private subnets for the things it may not (application servers, databases), connected to the internet through an Internet Gateway on the public side and a NAT Gateway on the private side, with route tables deciding which is which.

This is the most-watched video of the whole series, and the questions under it are always the same three: "my private instance cannot reach the internet", "my public instance is unreachable", and "what is the NAT Gateway costing me". All three are answered below. I do everything by hand first - that is how you learn what the one-click wizard and the Terraform module are doing - and then I show both shortcuts.

TL;DR

  • A subnet is public or private only because of its route table. 0.0.0.0/0 to an Internet Gateway makes it public; 0.0.0.0/0 to a NAT Gateway makes it private with outbound internet; no default route at all makes it isolated.
  • The build: VPC 10.0.0.0/16, two public /24s and two private /24s across two Availability Zones, one Internet Gateway, one NAT Gateway with an Elastic IP in a public subnet, two route tables. In my recording I built the same thing with 12.0.0.0/16: the public instance (12.0.1.27, public IP 3.64.216.164) answered SSH, and the private subnet's table had only the local route.
  • The two things that cost money are the NAT Gateway (about $0.045 per hour plus $0.045 per GB in N. Virginia, roughly $33 a month idle) and every public IPv4 address ($0.005 per hour, about $3.60 a month). Everything else on this page is free. The S3 gateway endpoint is the free way to keep backups and image pulls off the NAT.
  • Five addresses are reserved in every subnet, so a /24 has 251 usable; the console shows exactly that number on a fresh subnet.
  • The whole network is 15 Terraform resources, validated below with AWS provider 6.69.1, and the VPC Subnet Planner draws this exact layout with the reserved addresses already removed.
  • Not your exact case? If the notation is the problem, read what is CIDR first; if you already have the VPC and need to connect it to another one, go to VPC peering, Part-12.

Table of Content

  1. VPC vocabulary - VPC, subnet, route table, Internet Gateway, NAT Gateway
  2. Plan the CIDR blocks
  3. Step 1 - Create the VPC
  4. Step 2 - Create two public and two private subnets
  5. Step 3 - Create and attach the Internet Gateway
  6. Step 4 - Public route table - 0.0.0.0/0 to the Internet Gateway
  7. Step 5 - Create the NAT Gateway with an Elastic IP
  8. Step 6 - Private route table - 0.0.0.0/0 to the NAT Gateway
  9. Step 7 - Test it - bastion in public, app server in private
  10. Security groups vs network ACLs
  11. The shortcuts - "VPC and more" wizard and the AWS CLI
  12. What it costs - NAT Gateway, public IPv4, and the gateway endpoint trick
  13. Clean up in the right order
  14. Common VPC errors and how to fix them
  15. What broke when I ran this
  16. Conclusion



1. VPC vocabulary - VPC, subnet, route table, Internet Gateway, NAT Gateway

The target architecture - VPC 10.0.0.0/16, public and private subnets in two AZs, Internet Gateway, NAT Gateway, two route tables

  1. VPC - your own isolated slice of the AWS network in one region, defined by an IPv4 CIDR block (10.0.0.0/16). Nothing in it can talk to the internet until you say so. Every region has a default VPC (172.31.0.0/16, all subnets public) that exists so that "Launch instance" works on day one; real workloads get their own.
  2. Subnet - a slice of the VPC's address range that lives in exactly one Availability Zone. Instances are launched into subnets. A subnet is public or private purely because of its route table - there is no "type" checkbox.
  3. Route table - a list of destination → target rules. Every subnet is associated with one route table (the VPC's main route table if you do not say otherwise). Every route table has the un-deletable local route for the VPC's own CIDR.
  4. Internet Gateway (IGW) - the VPC's door to the internet, one per VPC. A subnet whose route table sends 0.0.0.0/0 to the IGW is a public subnet. Instances in it still need a public IPv4 address (or an Elastic IP) to be reachable.
  5. NAT Gateway - lets instances in private subnets start connections out to the internet (apt update, calling an API, pulling a container image) while nothing on the internet can start a connection in. It lives in a public subnet, has an Elastic IP, and is managed by AWS - no instance to patch.
  6. Security group and network ACL - the two firewalls, covered in section 10.

The flow for a packet from a private instance to the internet is: instance → private route table says 0.0.0.0/0 → nat-xxx → NAT Gateway in the public subnet swaps the source IP for its Elastic IP → public route table says 0.0.0.0/0 → igw-xxx → internet. Replies follow the state the NAT keeps. Keep this picture in mind and the errors in section 14 all make sense.


2. Plan the CIDR blocks

Five minutes of planning here saves a rebuild later, because a VPC CIDR cannot be changed (only extended with secondary blocks) and overlapping ranges make VPC peering and VPNs impossible. From the VPC CIDR docs -

  1. A VPC IPv4 CIDR is between /16 (65,536 addresses) and /28 (16). Use the private ranges 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.
  2. Each subnet reserves 5 addresses - the first four (network, VPC router, DNS, future) and the last (broadcast). A /24 gives you 251 usable, not 256.
  3. Do not reuse the default VPC's 172.31.0.0/16 or your office's range.
  4. Leave room - one VPC per environment, non-overlapping, e.g. 10.0.0.0/16 dev, 10.1.0.0/16 prod.

Our plan, two AZs so that an AZ outage does not take everything down -

SubnetCIDRAZRoute table
jhooq-public-1a10.0.1.0/24eu-central-1apublic
jhooq-public-1b10.0.2.0/24eu-central-1bpublic
jhooq-private-1a10.0.11.0/24eu-central-1aprivate
jhooq-private-1b10.0.12.0/24eu-central-1bprivate

The /16 leaves 10.0.3.0 to 10.0.255.0 for databases subnets, more AZs and future tiers. If CIDR notation is still fuzzy, what is CIDR is the ten-minute version; the rule of thumb is /24 = 256 addresses, each step down doubles, each step up halves.

I built this table by hand for years. Now I let the VPC Subnet Planner do it (that link opens it with this post's 10.0.0.0/16 and two zones already set). It takes AWS's five reserved addresses out of every subnet, keeps each tier in one contiguous block, shows the 86% of the VPC still free, and prints the cidrsubnet() call for every subnet, which is what the Terraform in section 11 uses:

The planner's layout of 10.0.0.0/16 across two zones with public, private and database tiers; 251 usable addresses per /24 after the five AWS reserves

The planner puts the private tier at 10.0.0.0/20 and the public one at 10.0.32.0/24 rather than at 10.0.1.0 and 10.0.11.0; both layouts are valid, and the planner's keeps every tier summarisable by one CIDR, which matters the day you write a network ACL for "all private subnets".



3. Step 1 - Create the VPC

Switch the console to eu-central-1 (or your region) and open VPC → Your VPCs → Create VPC (docs) -

  1. Resources to create - VPC only. (The other option, VPC and more, is the wizard in section 11 - we go manual first.)
  2. Name tag - jhooq-vpc.
  3. IPv4 CIDR block - IPv4 CIDR manual input → 10.0.0.0/16.
  4. IPv6 CIDR block - No IPv6 CIDR block for this tutorial (adding an Amazon-provided /56 later is one click).
  5. Tenancy - Default.
  6. Create VPC.

Then one setting people forget - select the VPC → Actions → Edit VPC settings → tick Enable DNS hostnames (Enable DNS resolution is already on). Without DNS hostnames your instances get no public DNS name and, later, interface endpoints and some services misbehave.

In the recording the VPC is test-vpc with 12.0.0.0/16, created exactly this way:

Create VPC in the recording: VPC only, name test-vpc, IPv4 CIDR 12.0.0.0/16, no IPv6, default tenancy

What AWS created for you along with the VPC: a main route table (just the local route), a default network ACL (allow all) and a default security group (allow from itself, all outbound). No subnets, no gateway.


4. Step 2 - Create two public and two private subnets

VPC → Subnets → Create subnet (configure subnets) -

  1. VPC ID - jhooq-vpc.
  2. Subnet name - jhooq-public-1a, Availability Zone - eu-central-1a, IPv4 subnet CIDR block - 10.0.1.0/24.
  3. Click Add new subnet three times for jhooq-public-1b / 1b / 10.0.2.0/24, jhooq-private-1a / 1a / 10.0.11.0/24, jhooq-private-1b / 1b / 10.0.12.0/24.
  4. Create subnet.

Now make the public ones actually hand out public IPs: select jhooq-public-1a → Actions → Edit subnet settings → tick Enable auto-assign public IPv4 address → Save. Repeat for jhooq-public-1b. Leave it off for the private subnets - that is half of what makes them private. (You can still override per instance at launch, but the subnet default is what Auto Scaling and most tooling rely on.)

Notice in the subnet list that all four currently use the main route table and show Available IPv4 addresses: 251.



5. Step 3 - Create and attach the Internet Gateway

VPC → Internet gateways → Create internet gateway (docs) -

  1. Name tag - jhooq-igw, Create internet gateway. Its state is Detached.
  2. The green banner offers Attach to a VPC - click it, choose jhooq-vpc, Attach internet gateway. State becomes Attached.

One IGW per VPC, one VPC per IGW. It is horizontally scaled and redundant by itself, costs nothing, and does two jobs: it is the route target for internet traffic, and it performs the one-to-one NAT between an instance's private IP and its public/Elastic IP (the instance itself never sees its public address - ip addr on the instance shows only 10.0.1.x).

The recording's IGW-test attached to test-vpc: state Attached, and still no route uses it

Attaching the IGW alone changes nothing - no route table points at it yet.


6. Step 4 - Public route table - 0.0.0.0/0 to the Internet Gateway

Do not add the internet route to the main route table - every new subnet would silently become public. Create a dedicated one (route tables) -

  1. VPC → Route tables → Create route table - Name jhooq-public-rt, VPC jhooq-vpc, Create.
  2. Open it → Routes tab → Edit routes → Add route - Destination 0.0.0.0/0, Target → Internet Gateway → jhooq-igw. Save changes. The table now reads -
110.0.0.0/16   local
20.0.0.0/0     igw-0123456789abcdef0

This is the moment in the recording. The target dropdown lists every kind of gateway a route can point at, and for a public subnet the answer is always the Internet Gateway:

Edit routes on RT-test-public: the target list offers Internet Gateway, NAT Gateway, Transit Gateway, Peering Connection and more

RT-test-public after saving: 12.0.0.0/16 local and 0.0.0.0/0 to igw-0541c0f53e1139052

  1. Subnet associations tab → Edit subnet associations → tick jhooq-public-1a and jhooq-public-1b → Save. Before you do, both subnets sit on the main route table, which is what the recording shows:

Edit subnet associations: test-public-subnet-1a 12.0.1.0/24 and test-private-subnet-1a 12.0.3.0/24, both still on the Main route table

Those two subnets are now public by definition. Routing picks the most specific match, so traffic to 10.0.x.x stays local and everything else goes to the IGW. The main route table keeps only the local route and becomes, in effect, the private one - but we will create an explicit private table in Step 6 so that nothing depends on the default.



7. Step 5 - Create the NAT Gateway with an Elastic IP

NAT Gateway - VPC → NAT gateways → Create NAT gateway -

  1. Name - jhooq-nat-1a.
  2. Subnet - jhooq-public-1a. This is the mistake to avoid - a NAT Gateway must be in a public subnet, because it needs the IGW route to reach the internet. Put it in a private subnet and the private instances will time out forever.
  3. Connectivity type - Public. (A private NAT Gateway, without an EIP, is for routing between VPCs/on-premises with overlapping ranges - not what we want.)
  4. Elastic IP allocation ID - click Allocate Elastic IP. This reserves a fixed public IPv4 address for the gateway - the address your private instances will appear as to the outside world, handy for allow-lists.
  5. Create NAT gateway. State goes Pending → Available in a minute or two.

A NAT Gateway starts at 5 Gbps and scales to 100 Gbps, handles one million packets per second scaling to 10 million, supports 55,000 simultaneous connections per destination per IPv4 address (NAT gateway basics), and is per Availability Zone. For production, create jhooq-nat-1b in jhooq-public-1b as well and give each private subnet its own route table pointing at the NAT in its AZ - otherwise an outage of 1a cuts off 1b's private instances too, and you pay cross-AZ data transfer for every byte. For this tutorial, one NAT is enough.


8. Step 6 - Private route table - 0.0.0.0/0 to the NAT Gateway

  1. Route tables → Create route table - Name jhooq-private-rt, VPC jhooq-vpc, Create.
  2. Edit routes → Add route - Destination 0.0.0.0/0, Target → NAT Gateway → jhooq-nat-1a. Save.
110.0.0.0/16   local
20.0.0.0/0     nat-0123456789abcdef0

In the recording I stopped one step earlier: RT-test-private was created with only the local route and no NAT Gateway, which is the fully isolated version of a private subnet. Instances in it can talk to the rest of the VPC and nothing else, and that is sometimes exactly right (databases). The NAT Gateway steps above are what you add when the private tier needs apt-get or an external API, and the Terraform in section 11 includes them.

RT-test-private in the recording: one route, 12.0.0.0/16 local, so the private subnet has no path to the internet in either direction

  1. Edit subnet associations → tick jhooq-private-1a and jhooq-private-1b → Save.

That is the whole network. Open the VPC → Resource map tab and you get the same picture as my diagram, drawn from your actual resources - four subnets, two route tables, the IGW and the NAT, with lines showing which subnet routes where. If a subnet is not where you expect, this tab shows it in two seconds.


9. Step 7 - Test it - bastion in public, app server in private

Proof beats theory. Launch two instances exactly as in Part-4 -

Bastion - jhooq-bastion, Ubuntu 24.04, t3.micro, key pair jhooq-key, Network settings → Edit → VPC jhooq-vpc, subnet jhooq-public-1a, Auto-assign public IP: Enable, new security group jhooq-bastion-sg with SSH from My IP.

App server - jhooq-app, same AMI and type and key, VPC jhooq-vpc, subnet jhooq-private-1a, Auto-assign public IP: Disable, new security group jhooq-app-sg with one inbound rule: SSH, Source = the bastion's security group jhooq-bastion-sg. Referencing a security group instead of an IP is the pattern - "anything wearing the bastion SG may SSH here".

Now test, from your laptop. This is the public half from the recording: the instance in test-public-subnet-1a got public IP 3.64.216.164 and private IP 12.0.1.27, and SSH worked on the first attempt:

 1rahulwagh@Rahuls-MacBook-Pro-2 .ssh % ssh -i "aws_ec2_terraform" ubuntu@3.64.216.164
 2The authenticity of host '3.64.216.164 (3.64.216.164)' can't be established.
 3ED25519 key fingerprint is SHA256:KWbTNtUj1khaV2t9N/n4ApYvJn4wl3c6MPCPLDqqk+g.
 4Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
 5Warning: Permanently added '3.64.216.164' (ED25519) to the list of known hosts.
 6Welcome to Ubuntu 22.04.2 LTS (GNU/Linux 5.19.0-1025-aws x86_64)
 7
 8  System information as of Thu Sep 21 19:19:56 UTC 2023
 9  System load:  0.005859375       Processes:             95
10  Usage of /:   20.6% of 7.57GB   Users logged in:       0
11  Memory usage: 24%               IPv4 address for eth0: 12.0.1.27

SSH into the public-subnet instance: public IP 3.64.216.164, eth0 shows the private address 12.0.1.27

The instance only knows its private address; the public one lives on the Internet Gateway's one-to-one NAT. The full test sequence with the private app server:

 1# 1. public subnet works - SSH to the bastion's public IP
 2ssh -i ~/.ssh/jhooq-key.pem ubuntu@<bastion-public-ip>
 3
 4# 2. the bastion reaches the internet through the IGW
 5curl -s https://checkip.amazonaws.com        # prints the bastion's own public IP
 6
 7# 3. hop to the private instance (forward your key with -A, or copy it to the bastion)
 8ssh -A ubuntu@<bastion-public-ip>            # from laptop, then on the bastion:
 9ssh ubuntu@10.0.11.x                         # the app server's private IP
10
11# 4. the private instance reaches the internet through the NAT
12curl -s https://checkip.amazonaws.com        # prints the NAT Gateway's ELASTIC IP, not the instance's
13sudo apt-get update                          # works - outbound only
1# 5. and the internet cannot reach the private instance - it has no public IP at all
2aws ec2 describe-instances --filters Name=tag:Name,Values=jhooq-app \
3  --query 'Reservations[].Instances[].[PrivateIpAddress,PublicIpAddress]' --output text
4# 10.0.11.23    None

Step 4 is the key observation - the private server's outbound traffic leaves with the NAT's Elastic IP. That is what NAT (network address translation) means, and it is why a NAT Gateway cannot be used for inbound traffic. If step 4 hangs, go straight to section 14, errors 1 and 2.

Instead of SSH-hopping, the modern options from Part-4 work here too - EC2 Instance Connect Endpoint (create one in a private subnet, then the console's Connect button reaches jhooq-app directly) or Session Manager via the instance role - and then you do not need a bastion or port 22 at all.


10. Security groups vs network ACLs

The VPC has two firewall layers and people mix them up constantly -

Security groupNetwork ACL
Attached tothe instance's network interfacethe subnet
Rulesallow onlyallow and deny
Statestateful - replies are automatically allowedstateless - you must allow the return traffic (ephemeral ports 1024-65535)
Evaluationall rules togetherin rule-number order, first match wins, * deny at the end
Can referenceIPs and other security groupsIPs only
Defaultnew SG: deny all inbound, allow all outbounddefault NACL: allow all both ways

Use security groups for 99% of your rules - they are what the bastion/app pattern above uses. Use a network ACL for the rare blunt instrument: blocking a specific IP range from an entire subnet, or compliance rules that demand a subnet-level deny. If you ever write a NACL, remember the stateless part - an inbound allow 443 needs an outbound allow 1024-65535, or the responses never leave.



11. The shortcuts - "VPC and more" wizard and the AWS CLI

Now that you know what each piece does, use the shortcuts.

The console wizard - Create VPC → Resources to create → VPC and more. One form builds everything from Steps 1-6: Name tag auto-generation (jhooq → jhooq-vpc, jhooq-subnet-public1-eu-central-1a ...), IPv4 CIDR 10.0.0.0/16, Number of Availability Zones 2, Number of public subnets 2, Number of private subnets 2, NAT gateways - None, In 1 AZ or 1 per AZ, VPC endpoints - S3 Gateway (keep it, see section 12), DNS options both on. The Preview pane draws the resource map before you click Create VPC. It produces exactly the layout of this post, with a separate private route table per AZ.

The AWS CLI - the same steps as commands, straight from the docs, condensed -

 1VPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 \
 2  --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=jhooq-vpc}]' \
 3  --query Vpc.VpcId --output text)
 4aws ec2 modify-vpc-attribute --vpc-id "$VPC_ID" --enable-dns-hostnames
 5
 6PUB_A=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.1.0/24  --availability-zone eu-central-1a --query Subnet.SubnetId --output text)
 7PRV_A=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.11.0/24 --availability-zone eu-central-1a --query Subnet.SubnetId --output text)
 8aws ec2 modify-subnet-attribute --subnet-id "$PUB_A" --map-public-ip-on-launch
 9
10IGW_ID=$(aws ec2 create-internet-gateway --query InternetGateway.InternetGatewayId --output text)
11aws ec2 attach-internet-gateway --vpc-id "$VPC_ID" --internet-gateway-id "$IGW_ID"
12
13PUB_RT=$(aws ec2 create-route-table --vpc-id "$VPC_ID" --query RouteTable.RouteTableId --output text)
14aws ec2 create-route --route-table-id "$PUB_RT" --destination-cidr-block 0.0.0.0/0 --gateway-id "$IGW_ID"
15aws ec2 associate-route-table --route-table-id "$PUB_RT" --subnet-id "$PUB_A"
16
17EIP_ID=$(aws ec2 allocate-address --domain vpc --query AllocationId --output text)
18NAT_ID=$(aws ec2 create-nat-gateway --subnet-id "$PUB_A" --allocation-id "$EIP_ID" --query NatGateway.NatGatewayId --output text)
19aws ec2 wait nat-gateway-available --nat-gateway-ids "$NAT_ID"
20
21PRV_RT=$(aws ec2 create-route-table --vpc-id "$VPC_ID" --query RouteTable.RouteTableId --output text)
22aws ec2 create-route --route-table-id "$PRV_RT" --destination-cidr-block 0.0.0.0/0 --nat-gateway-id "$NAT_ID"
23aws ec2 associate-route-table --route-table-id "$PRV_RT" --subnet-id "$PRV_A"

(Add the 1b subnets the same way.) And the whole thing is 15 resources in Terraform, with the subnets derived from the VPC CIDR instead of typed, and the free S3 gateway endpoint from section 12 included:

 1resource "aws_subnet" "public" {
 2  count                   = length(var.azs)
 3  vpc_id                  = aws_vpc.this.id
 4  availability_zone       = var.azs[count.index]
 5  cidr_block              = cidrsubnet(var.vpc_cidr, 8, count.index + 1)   # 10.0.1.0/24, 10.0.2.0/24
 6  map_public_ip_on_launch = true
 7}
 8
 9resource "aws_subnet" "private" {
10  count             = length(var.azs)
11  vpc_id            = aws_vpc.this.id
12  availability_zone = var.azs[count.index]
13  cidr_block        = cidrsubnet(var.vpc_cidr, 8, count.index + 11)        # 10.0.11.0/24, 10.0.12.0/24
14}
15
16resource "aws_route_table" "public" {
17  vpc_id = aws_vpc.this.id
18  route {
19    cidr_block = "0.0.0.0/0"
20    gateway_id = aws_internet_gateway.this.id
21  }
22}
23
24resource "aws_nat_gateway" "this" {
25  allocation_id = aws_eip.nat.id
26  subnet_id     = aws_subnet.public[0].id      # a NAT Gateway lives in a PUBLIC subnet
27  depends_on    = [aws_internet_gateway.this]
28}
29
30resource "aws_route_table" "private" {
31  vpc_id = aws_vpc.this.id
32  route {
33    cidr_block     = "0.0.0.0/0"
34    nat_gateway_id = aws_nat_gateway.this.id
35  }
36}
37
38resource "aws_vpc_endpoint" "s3" {
39  vpc_id            = aws_vpc.this.id
40  service_name      = "com.amazonaws.eu-central-1.s3"
41  vpc_endpoint_type = "Gateway"
42  route_table_ids   = [aws_route_table.private.id]
43}

Validated and planned on 2026-10-17 with Terraform 1.16.2 and AWS provider 6.69.1 (mock credentials, nothing created):

 1$ terraform validate
 2Success! The configuration is valid.
 3
 4$ terraform plan
 5  # aws_eip.nat will be created
 6  # aws_internet_gateway.this will be created
 7  # aws_nat_gateway.this will be created
 8  # aws_route_table.private will be created
 9  # aws_route_table.public will be created
10  # aws_subnet.private[0] will be created
11  # aws_subnet.public[0] will be created
12  # aws_vpc.this will be created
13  # aws_vpc_endpoint.s3 will be created
14  ...
15Plan: 15 to add, 0 to change, 0 to destroy.
16
17Outputs:
18subnets = {
19  "private" = ["10.0.11.0/24", "10.0.12.0/24"]
20  "public"  = ["10.0.1.0/24", "10.0.2.0/24"]
21}

The resources are documented at aws_nat_gateway, or use one call to the community terraform-aws-modules/vpc module. My ALB and SSL guide builds this exact VPC in Terraform before putting a load balancer in the public subnets, and the Google Cloud equivalent (where subnets are regional, not zonal, and there is no public/private subnet distinction) is in GCP VPC peering.


12. What it costs - NAT Gateway, public IPv4, and the gateway endpoint trick

The VPC, subnets, route tables, Internet Gateway, security groups and NACLs are free. Two things on this page are not -

  1. NAT Gateway - from the pricing page, you pay per hour the gateway exists and per GB it processes, plus the normal data transfer out. In us-east-1 that is $0.045 per hour (about $33 a month for one gateway doing nothing) and $0.045 per GB processed. Two NAT Gateways for HA double the hourly part. This is the line item that surprises people on the first bill of a "free tier" lab - delete the NAT Gateway when you are done (section 13).
  2. Public IPv4 addresses - $0.005 per hour each (about $3.60 a month) for every public IP and Elastic IP, including the NAT Gateway's, since February 2024. Fewer public IPs is both cheaper and safer.

Two ways AWS itself recommends to cut NAT cost -

  • Gateway endpoints for S3 and DynamoDB are free. Traffic from private subnets to S3 and DynamoDB goes through the endpoint instead of the NAT, so you pay nothing per GB for backups, logs, container layers in ECR (which are stored in S3) and so on. The wizard adds the S3 one by default; by hand: VPC → Endpoints → Create endpoint → AWS services → com.amazonaws.eu-central-1.s3 (Gateway) → tick the private route tables.
  • Keep traffic in one AZ - a NAT in 1a serving instances in 1b adds cross-AZ data charges; one NAT per AZ with per-AZ route tables avoids them. For other AWS services with heavy traffic, interface endpoints (PrivateLink) cost per hour but can still beat NAT per-GB charges - that is Part-19 and Part-20 of the video series.

Use the AWS Pricing Calculator for your region; the ratios above hold everywhere.


13. Clean up in the right order

Dependencies mean you cannot just delete the VPC. The order -

  1. Terminate the EC2 instances (jhooq-bastion, jhooq-app).
  2. Delete the NAT Gateway (NAT gateways → Actions → Delete) and wait until its state is Deleted - this is the one that costs money every hour.
  3. Release the Elastic IP (Elastic IPs → Actions → Release) - otherwise it keeps billing; how to release an Elastic IP if it refuses because something is still attached.
  4. Delete any VPC endpoints and Instance Connect endpoints.
  5. Delete the VPC (Your VPCs → Actions → Delete VPC). The console lists and deletes the subnets, route tables, IGW, security groups and NACLs for you, after you type delete.

If the VPC deletion fails with a dependency error, a network interface is usually left behind - Network interfaces in the EC2 console, find the ones in jhooq-vpc, detach and delete (error 9 below). The default VPC - leave it alone, or recreate it later with Actions → Create default VPC if you deleted it.


14. Common VPC errors and how to fix them

1. Private instance cannot reach the internet - apt update and curl time out - Check in this order: (a) the private subnet's route table has 0.0.0.0/0 → nat-... and the subnet is associated with that table; (b) the NAT Gateway is in a public subnet whose table routes 0.0.0.0/0 → igw-...; (c) the NAT Gateway state is Available; (d) the instance's security group allows outbound (default yes) and the NACL allows ephemeral return ports. 95% of cases are (a) or (b).

2. Private instance reaches the internet only sometimes / very slowly - The NAT is in another AZ, or you hit the 55,000 connections-per-destination limit (ErrorPortAllocation in the NAT Gateway CloudWatch metrics). One NAT per AZ; multiple EIPs on the NAT for the port limit.

3. Public instance - ssh: connect ... Connection timed out - It has no public IP (subnet auto-assign off and you did not enable it at launch - the fix is an Elastic IP or a relaunch), or the subnet's route table has no IGW route, or the security group lacks port 22 from your IP, or the IGW is detached. The Resource map shows the routing part instantly.

4. Network vpc-... has no internet gateway attached when creating a NAT Gateway or an internet-facing load balancer -** Attach the IGW first (Step 3).

5. The CIDR '10.0.1.0/24' conflicts with another subnet / InvalidSubnet.Conflict - Overlapping subnet ranges inside the VPC. Plan them as in section 2; my InvalidSubnet.Range post covers the Terraform version.

6. InvalidParameter: Security group sg-... and subnet subnet-... belong to different networks - You picked a security group from the default VPC for an instance in jhooq-vpc. Security groups are per VPC - create one in the right VPC. Full write-up.

7. AddressLimitExceeded: The maximum number of addresses has been reached - Five Elastic IPs per region by default. Release unused ones (how) or request a quota increase.

8. VpcLimitExceeded - Five VPCs per region by default (VPC quotas). Delete old lab VPCs or request an increase.

9. DependencyViolation: The vpc has dependencies and cannot be deleted - An ENI, NAT Gateway, endpoint, or a load balancer / RDS instance still exists in it. Follow the order in section 13; find leftovers under EC2 → Network interfaces filtered by VPC.

10. Instances in the same VPC cannot ping each other - Security groups: ICMP is not allowed by default; add an inbound rule All ICMP - IPv4 from the other instance's SG. Routing inside the VPC is always there via the local route - it is never the route table.

11. My NAT Gateway bill is high although I barely use the instances - Something is pulling data through it continuously - container image pulls, S3 backups, package mirrors. Add the free S3 gateway endpoint, check the BytesOutToDestination metric, and consider interface endpoints for ECR, CloudWatch and SSM.

12. DNS names do not resolve / no public DNS name on the instance - Enable DNS hostnames on the VPC (Step 1).


15. What broke when I ran this

The console build and the SSH login are from my recording of September 2023 in Frankfurt; the Terraform plan and the prices are from 2026-10-17.

1. My own diagram said 12.0.1.0/16, which is not a valid block. The slide in the recording labels the VPC 12.0.1.0/16 while the console shows 12.0.0.0/16. A /16 must start on a .0.0 boundary; AWS would have refused the slide's version with is not a valid IPv4 CIDR block. Nobody noticed for two years, which is the best argument for letting a tool draw the diagram from the real CIDRs.

2. The recording has no NAT Gateway. I built the public side, the private subnet with a local-only route table, and the public instance, then deleted everything. The NAT Gateway steps in sections 7 and 8 and the private-instance test in section 9 are the same build I run in the Terraform here and in the NAT Gateway deep dive; I have marked which outputs come from where.

3. Both subnets were on the main route table until I moved them. The subnet associations dialog shows test-public-subnet-1a and test-private-subnet-1a both on Main. Had I added the internet route to the main table instead of creating RT-test-public, the private subnet would have become public without anyone touching it. Creating a dedicated public table and associating only the public subnets is the step that keeps that from happening.

4. The Terraform plan took 33.6 seconds for 15 resources. None of it was AWS; it is the provider start-up, the same floor I measured in the user_data post. Budget for it in CI rather than wondering whether the plan hung.


16. Conclusion

To summarise Part-5 -

  1. A VPC is your isolated network in a region; subnets live in one AZ each; whether a subnet is public or private is decided only by its route table.
  2. Plan the CIDR first - /16 for the VPC, /24 per subnet, two AZs, five reserved addresses per subnet, no overlaps with anything you may peer with.
  3. Public subnets - a route table with 0.0.0.0/0 → Internet Gateway, plus auto-assign public IP. Private subnets - a route table with 0.0.0.0/0 → NAT Gateway, and the NAT Gateway itself sits in a public subnet with an Elastic IP.
  4. Prove it with a bastion in public and an app server in private - the private server's traffic leaves with the NAT's IP, and nothing can connect to it from outside.
  5. Security groups (stateful, allow-only, on the instance) for almost everything; NACLs (stateless, on the subnet) for the rare deny.
  6. The "VPC and more" wizard, the CLI and Terraform build the same thing in a minute - and the NAT Gateway is the part that costs money, so delete it after the lab and add the free S3 gateway endpoint in real deployments.

The official references are the VPC User Guide, create a VPC, NAT gateways and route tables. From here the series goes to launch templates and Auto Scaling, WAF, VPC peering, Transit Gateway and the NAT Gateway deep dive - and for the infrastructure-as-code version of this network with a load balancer on top, Terraform - setting up an ALB and SSL.


More videos on this topic - the same build in one sitting from my 2024 Solutions Architect series (EC2, VPC, subnets, route tables, Internet Gateway, NAT Gateway, jump host), and the one-minute explainer of the Internet Gateway -



Did this save you a debugging session? Stay in the loop -

AWS step by step series -

  1. Part-1 : AWS IAM user - create a user, group, policy, access keys and MFA
  2. Part-2 : AWS Organizations - multi-account setup, OUs and SCPs
  3. Part-3 : AWS assume IAM role - trust policy, switch role in console and CLI
  4. Part-4 : How to launch an EC2 instance - key pair, security group, SSH
  5. Part-5 : AWS VPC - public and private subnets, Internet Gateway, NAT Gateway, route tables
  6. Part-8 : EC2 launch template - versions, default version, source template, SSM parameter AMI
  7. Part-10 : EC2 Auto Scaling - launch template, Auto Scaling group, target tracking, ALB
  8. Part-11 : AWS WAF - web ACL, managed rules, rate limiting, geo blocking
  9. Part-12 : AWS VPC Peering - connect two VPCs, routes, security groups, DNS
  10. Part-13 : AWS Transit Gateway - hub-and-spoke for many VPCs and on-premises
  11. Part-14 : AWS NAT Gateway deep dive - public vs private, limits, cost, troubleshooting
  12. Part-15 : Amazon Route 53 - hosted zones, records, alias, routing policies, health checks
  13. Part-16 : AWS security groups - inbound and outbound rules, stateful, referencing, quotas
  14. Part-16 : AWS Certificate Manager - free TLS certificates for ALB, CloudFront and API Gateway
  15. Part-17 : AWS Lambda - function URLs, environment variables and layers
  16. Part-18 : Network Load Balancer - setup, and ALB vs NLB
  17. Part-19 : VPC endpoints - gateway and interface endpoints (PrivateLink) instead of NAT
  18. Part-20 : AWS PrivateLink - publish your own service with an endpoint service and NLB
  19. Part-20 : Amazon EBS volumes - types, attach, mount, resize, snapshots, encryption
  20. Part-21 : VPC Flow Logs - CloudWatch Logs, S3, record format, Logs Insights, Athena
  21. Part-21 : EC2 Spot Instances - pricing, interruptions, mixed instances groups
  22. Part-23 : AWS Global Accelerator - static anycast IPs in front of ALBs in two regions, traffic dials, weights
  23. Part-24 : AWS Control Tower - landing zone, controls, Account Factory, Identity Center
  24. Part-25 : AWS Cloud WAN - global network, core network policy, dev/prod/shared segments, tag-based attachments across three regions

Networking fundamentals -

  1. What is a VPC and a subnet? AWS networking in five minutes
  2. What is CIDR? Calculate IP ranges for VPCs and subnets
  3. VPC Subnet Planner - the free tool I use to size the VPC and subnet CIDRs in every part of this series (AWS, Azure, GCP rules built in)
  4. What is NAT? Static NAT, dynamic NAT and PAT explained

More AWS guides -

  1. What is AWS CloudFormation? Templates, stacks, change sets, drift, StackSets
  2. Learn AWS S3 - the complete course
  3. AWS API Gateway - REST API with Lambda, authorizers, Terraform
  4. AWS Advanced Networking Specialty (ANS-C01) - course companion
  5. AWS ECS and Fargate - how to deploy a Docker container
  6. AWS S3 - how to host a static website
  7. Terraform create EC2 instance on AWS
  8. Terraform AWS IAM - users, roles and policies
  9. Terraform and AWS multi-account setup
  10. Terraform - setting up an ALB and SSL