Skip to content

Lesson 5 of 30Core services

VPC Networking

Design a VPC with public and private subnets, do CIDR math, and trace exactly how packets reach your app and database.

18 min read0/5 questions

Every EC2 instance, RDS database, load balancer and VPC-attached Lambda lives inside a VPC, and most "it times out" bugs on AWS are networking: a missing route, a security group that does not allow the port, a private subnet with no way out. This lesson is the one that turns those mysteries into a checklist.

A VPC is your private network

A VPC (Virtual Private Cloud) is an isolated network inside one Region that belongs to your account. You pick its IP address range, carve it into subnets, and decide what can talk to what. Every account comes with a default VPC in each Region so you can launch things immediately, but real projects create their own.

A subnet is a slice of the VPC's address range that lives in exactly one Availability Zone. That is the key link to Cloud Basics: to spread across two AZs, you need subnets in two AZs.

CIDR: how address ranges are written

IP ranges are written in CIDR notation: 10.0.0.0/16. An IPv4 address is 32 bits. The number after the slash is how many leading bits are fixed; the rest are free to vary.

  • 10.0.0.0/16: first 16 bits fixed, 16 free, so 2^16 = 65,536 addresses (10.0.0.0 to 10.0.255.255).
  • 10.0.1.0/24: 24 fixed, 8 free, so 256 addresses (10.0.1.0 to 10.0.1.255).
  • 0.0.0.0/0: nothing fixed, so every IPv4 address. In a route table or firewall rule it means "the internet".

Bigger number after the slash, smaller block. A VPC can be /16 to /28, and subnets are carved out of it. Use the private ranges 10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16, and do not overlap with other VPCs or your office network if you will ever connect them.

Pythoncidr.py
def to_int(ip): a, b, c, d = (int(x) for x in ip.split(".")) return (a << 24) | (b << 16) | (c << 8) | d def to_ip(n): return ".".join(str((n >> shift) & 255) for shift in (24, 16, 8, 0)) def describe(cidr): net, prefix = cidr.split("/") prefix = int(prefix) size = 2 ** (32 - prefix) mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF first = to_int(net) & mask print(f"{cidr:>16} {to_ip(first)} - {to_ip(first + size - 1)} ({size} addresses, {size - 5} usable in AWS)") describe("10.0.0.0/16")describe("10.0.1.0/24")describe("10.0.2.0/27")
Output
Press Run (⌘ Enter) to see what happens.

Why "usable"? AWS reserves 5 addresses in every subnet: the first four (network address, VPC router, DNS, reserved) and the last. A /24 subnet gives you 251 IPs, not 256.

Predict the outputPython

How many total addresses (before AWS's 5 reserved) are in 10.0.0.0/20?

print(2 ** (32 - 20))
Need a nudge? Hints walk you through it.

Splitting a VPC into subnets is just choosing non-overlapping blocks inside it:

Pythonsplit.py
def to_int(ip): a, b, c, d = (int(x) for x in ip.split(".")) return (a << 24) | (b << 16) | (c << 8) | d def to_ip(n): return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0)) def split(vpc_cidr, new_prefix, count): base = to_int(vpc_cidr.split("/")[0]) step = 2 ** (32 - new_prefix) return [f"{to_ip(base + i * step)}/{new_prefix}" for i in range(count)] names = ["public-a", "public-b", "app-a", "app-b", "db-a", "db-b"]for name, block in zip(names, split("10.0.0.0/16", 24, 6)): print(f"{name:<9} {block}")
Output
Press Run (⌘ Enter) to see what happens.

Public vs private subnets

Here is the surprise: there is no "public" checkbox on a subnet. A subnet is public if its route table sends internet traffic (0.0.0.0/0) to an internet gateway. Otherwise it is private.

  • An internet gateway (IGW) connects the VPC to the internet, in both directions. Resources in a public subnet with a public IP can be reached from outside.
  • A route table is a list of rules: "traffic for this destination goes to that target". Every subnet is associated with one. Every route table has a local route so everything inside the VPC can reach everything else.
  • A NAT gateway sits in a public subnet and lets resources in private subnets make outbound connections (to download packages, call Stripe) while nothing on the internet can connect in.
Route table forDestinationTarget
Public subnets10.0.0.0/16local
Public subnets0.0.0.0/0igw-0abc (internet gateway)
Private subnets10.0.0.0/16local
Private subnets0.0.0.0/0nat-0def (NAT gateway)
Private subnetsS3 prefix listvpce-0123 (gateway endpoint)

The rule of thumb: only load balancers and NAT gateways go in public subnets. App servers, containers and databases go in private ones.

The classic three-tier VPC

Three-tier VPC across two AZs
VPC 10.0.0.0/16Public subnets (AZ a | AZ b)Private app subnetsPrivate DB subnetsUserUserInternet GWInternet GWALB: public a+bALBpublic a+bNAT gateway: public bNAT gatewaypublic bApp: 10.0.2.xApp10.0.2.xApp: 10.0.3.xApp10.0.3.xRDS primary: 10.0.4.xRDS primary10.0.4.xRDS standby: 10.0.5.xRDS standby10.0.5.xS3 endpoint: gateway typeS3 endpointgateway typeS3S3Stripe APIStripe APIHTTPS:8000:5432sync

A request enters through the internet gateway. The only public thing it can reach is the ALB in the public subnets.

1/5
Quick check
An app in a private subnet runs pip install and it hangs until it times out. The subnet's route table has only the local route. What is missing?
Need a nudge? A hint rules out a wrong answer.

Security groups vs network ACLs

You met security groups in the EC2 lesson. Subnets have a second, coarser firewall: the network ACL (NACL).

Security groupNetwork ACL
Attached toA network interface (instance, task, RDS)A subnet
RulesAllow onlyAllow and deny, numbered, evaluated in order
StateStateful: replies allowed automaticallyStateless: must allow return traffic (ephemeral ports 1024-65535)
Can referenceOther security groupsOnly CIDR ranges
Typical useYour main tool, every dayRare: blocking a bad IP range subnet-wide

Most teams leave NACLs at their default (allow all) and do everything with security groups. If you do touch NACLs, remember they are stateless: allowing inbound 443 is not enough, the response goes out on a high ephemeral port that must also be allowed.

Match the pairs0/4 matched

Security group or NACL?

Choose an item, then its match on the other side.

VPC endpoints: reach AWS services privately

Your private app calls S3, DynamoDB, Secrets Manager or ECR. Without help, that traffic goes out through the NAT gateway to the public service endpoints. VPC endpoints keep it inside AWS:

  • Gateway endpoints for S3 and DynamoDB only. They are a route table entry and are free. Add them to every VPC.
  • Interface endpoints (AWS PrivateLink) for most other services (Secrets Manager, ECR, SQS, CloudWatch Logs). They put a network interface with a private IP in your subnet. They bill per hour per AZ plus per GB, so add them when they save NAT traffic or when you need no internet path at all.
Quick check
Your ECS tasks in private subnets pull a 1 GB image from ECR on every deploy and push many GB of logs to S3. Your NAT bill is high. What is the cheapest first fix?
Need a nudge? A hint rules out a wrong answer.

The VPC as code

Nobody should click all of those route tables together. With AWS CDK in TypeScript, the whole three-tier VPC is a few lines:

lib/network-stack.ts
import * as ec2 from "aws-cdk-lib/aws-ec2";
 
const vpc = new ec2.Vpc(this, "AppVpc", {
  ipAddresses: ec2.IpAddresses.cidr("10.0.0.0/16"),
  maxAzs: 2,
  natGateways: 1, // one to save money in dev; one per AZ in prod
  subnetConfiguration: [
    { name: "public", subnetType: ec2.SubnetType.PUBLIC, cidrMask: 24 },
    { name: "app", subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, cidrMask: 24 },
    { name: "db", subnetType: ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 24 },
  ],
  gatewayEndpoints: { S3: { service: ec2.GatewayVpcEndpointAwsService.S3 } },
});

PRIVATE_WITH_EGRESS means "private, with a route to a NAT gateway". PRIVATE_ISOLATED means no route out at all, which is right for databases.

Put it in order4 steps

Your app cannot reach its RDS database (connection times out). Order the checks from the inside out.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

Is this IP in the CIDR block?

Write in_cidr(ip, cidr) that returns whether an IPv4 address is inside a CIDR block, without using an IP library.

A CIDR block like 10.0.0.0/16 means: the first 16 bits are fixed, the rest can be anything. Turn both addresses into 32-bit integers, keep only the first prefix bits of each (a mask), and compare.

in_cidr("10.0.1.25", "10.0.0.0/16")        →  True
in_cidr("10.1.0.1", "10.0.0.0/16")         →  False
in_cidr("172.31.255.255", "172.16.0.0/12") →  True
in_cidr("8.8.8.8", "0.0.0.0/0")            →  True   (/0 matches everything)
def in_cidr(ip: str, cidr: str) -> bool: # Convert "a.b.c.d" to one 32-bit integer, then compare the first prefix bits. pass
ChallengeEasy

Usable IPs in a subnet

A subnet's CIDR block decides how many addresses it holds: a /p block has 2^(32 - p) addresses. AWS reserves 5 in every subnet (the network address, the VPC router, DNS, one for future use, and the last address).

Write usable_ips(cidr) that returns how many addresses you can actually give to resources. AWS subnets must be between /16 and /28, and your inputs will always be in that range.

usable_ips("10.0.1.0/24")   →  251
usable_ips("10.0.0.0/28")   →  11
usable_ips("10.0.0.0/16")   →  65531
def usable_ips(cidr: str) -> int: pass
Key terms
VPC
Your isolated private network in one Region, with an address range you choose.
CIDR block
An IP range like 10.0.0.0/16: the number after / is how many leading bits are fixed.
public subnet
A subnet whose route table sends 0.0.0.0/0 to an internet gateway.
NAT gateway
Lets private subnets make outbound internet connections. Billed per hour and per GB.
route table
Rules mapping destination ranges to targets (local, IGW, NAT, endpoint) for the subnets associated with it.
VPC endpoint
Private access to AWS services. Gateway type (S3, DynamoDB) is free; interface type bills hourly.