Networking: VPC, subnets and security

VPC
virtual private cloud

Mid-level Frequently asked 5 min

On this page

The question

What is a VPC, and how would you lay one out for a typical web service?

30-second answer

A VPC is your own isolated private network in a region, with an address range such as 10.0.0.0/16 split into subnets, one set per availability zone. For a web service I use three tiers: public subnets with only the load balancer and NAT gateways, private app subnets for the instances or containers, and private data subnets for databases with no route out. Route tables decide what is public; security groups allow only named callers between tiers.

Understand it

From the internet to a private service

Step by step

A client calls api.shop.example. DNS answers with the public address of the load balancer, the only part of this VPC (virtual private cloud) reachable from the internet.

Step 1 of 7
View as text

A VPC, 10.0.0.0/16: a public subnet with the load balancer and NAT gateway, a private app subnet and a private data subnet, below an internet gateway, a client and a payments API.

A client calls api.shop.example. DNS answers with the public address of the load balancer, the only part of this VPC (virtual private cloud) reachable from the internet.

The packet enters through the internet gateway. A subnet is public only because its route table sends 0.0.0.0/0 to this gateway.

The load balancer’s security group allows port 443 from anywhere. It terminates TLS and picks a healthy app instance in the private subnet.

The app’s security group allows port 8080 only from the load balancer’s security group, a reference, not an address range. Nothing else may connect.

The app queries PostgreSQL in the data subnet. Its group allows 5432 only from the app’s group, and its subnet has no route to the internet at all.

To call the payments API, the app’s private route sends 0.0.0.0/0 to the NAT gateway, which goes out through the internet gateway. Replies return; new inbound connections cannot.

An attacker tries the app instance directly. It has only a private address, no route leads to it from the internet, and its security group would drop the packet anyway.

A VPC, 10.0.0.0/16: a public subnet with the load balancer and NAT gateway, a private app subnet and a private data subnet, below an internet gateway, a client and a payments API.

A client calls api.shop.example. DNS answers with the public address of the load balancer, the only part of this VPC (virtual private cloud) reachable from the internet.

The packet enters through the internet gateway. A subnet is public only because its route table sends 0.0.0.0/0 to this gateway.

The load balancer’s security group allows port 443 from anywhere. It terminates TLS and picks a healthy app instance in the private subnet.

The app’s security group allows port 8080 only from the load balancer’s security group, a reference, not an address range. Nothing else may connect.

The app queries PostgreSQL in the data subnet. Its group allows 5432 only from the app’s group, and its subnet has no route to the internet at all.

To call the payments API, the app’s private route sends 0.0.0.0/0 to the NAT gateway, which goes out through the internet gateway. Replies return; new inbound connections cannot.

An attacker tries the app instance directly. It has only a private address, no route leads to it from the internet, and its security group would drop the packet anyway.

Takeaway: Only the load balancer sits in a public subnet. Apps and databases live in private subnets, reachable only through security group rules that name their callers, and they reach out through a NAT gateway.

A VPC, where subnets are public or private only by their routesThe internet reaches the VPC through an internet gateway. The public subnet's route table sends all traffic to the internet gateway, so the load balancer and the NAT gateway there can be reached. The private app subnet's route table sends outbound traffic to the NAT gateway, so the app can call out but cannot be called in. The private data subnet has no route out at all. Security groups on each resource then allow only named callers.calls out via NATInternetInternet gatewayPublic subnetroute 0.0.0.0/0 toIGW:load balancer, NATPrivate app subnetroute 0.0.0.0/0 toNAT:orders appPrivate data subnetno route out:PostgreSQL
A VPC, where subnets are public or private only by their routesThe internet reaches the VPC through an internet gateway. The public subnet's route table sends all traffic to the internet gateway, so the load balancer and the NAT gateway there can be reached. The private app subnet's route table sends outbound traffic to the NAT gateway, so the app can call out but cannot be called in. The private data subnet has no route out at all. Security groups on each resource then allow only named callers.calls out via NATInternetInternet gatewayPublic subnetroute 0.0.0.0/0 toIGW:load balancer, NATPrivate app subnetroute 0.0.0.0/0 toNAT:orders appPrivate data subnetno route out:PostgreSQL
A VPC: subnets are public or private only by their routes
ConceptAWS (Amazon Web Services)AzureGCP (Google Cloud Platform)
Private networkVPC (virtual private cloud)Virtual network (VNet)VPC network
Stateful firewall per resourceSecurity groupNetwork security groupVPC firewall rules
Outbound-only internet accessNAT gatewayNAT GatewayCloud NAT
Private access to managed servicesVPC endpoints, PrivateLinkPrivate EndpointPrivate Service Connect

In code

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "public_a" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "eu-west-1a"
}

resource "aws_subnet" "app_a" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.11.0/24"
  availability_zone = "eu-west-1a"
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.main.id # public: the internet can reach in
  }
}

resource "aws_route_table" "private" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.a.id # private: out only, through NAT (network address translation)
  }
}
Terraform: one VPC, a public and a private subnet, and the two route tables that make them so
resource "aws_vpc_security_group_ingress_rule" "db_open" {
  security_group_id = aws_security_group.db.id
  from_port         = 5432
  to_port           = 5432
 Wrong   cidr_ipv4         = "0.0.0.0/0" # wrong: any address on the internet may try the password
  ip_protocol       = "tcp"
}

resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
 Right   referenced_security_group_id = aws_security_group.app.id # right: only members of the app group
  from_port                    = 5432
  to_port                      = 5432
  ip_protocol                  = "tcp"
}
Security groups name their callers: the database accepts the app group, not an address range
nc -vz orders-db.internal 5432               # "succeeded": route and security groups allow it
nc -vz -w 5 orders-db.internal 5432          # timeout: dropped by a security group or a missing route
curl -sS --max-time 5 https://api.payments.example/health   # outbound through NAT
curl -s https://checkip.amazonaws.com        # prints the NAT gateway's public IP, not the instance's
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-0abc12 \
  --query 'RouteTables[].Routes[].[DestinationCidrBlock,GatewayId,NatGatewayId]'
From inside the app instance: test each hop before blaming the code
Calling out from a private subnet, and why nothing can call inThe app in a private subnet sends a request to the payments API. Its route table sends it to the NAT gateway, which replaces the private source address with its own public one and sends it out through the internet gateway. The reply comes back to the NAT gateway, which remembers the connection and returns it to the app. A connection opened from the internet towards the app has no route and is dropped.Payments APIInternet gatewayNAT gatewayorders app, 10.0.11.23a new connection from the internetto 10.0.11.23: no route, droppedPOST /charges (route 0.0.0.0/0)source rewritten to the NAT's public IPPOST /charges201, back through NAT and its connection table
Calling out from a private subnet, and why nothing can call inThe app in a private subnet sends a request to the payments API. Its route table sends it to the NAT gateway, which replaces the private source address with its own public one and sends it out through the internet gateway. The reply comes back to the NAT gateway, which remembers the connection and returns it to the app. A connection opened from the internet towards the app has no route and is dropped.Payments APIInternet gatewayNAT gatewayorders app, 10.0.11.23a new connection from the internetto 10.0.11.23: no route, droppedPOST /charges (route 0.0.0.0/0)source rewritten to the NAT's public IPPOST /charges201, back through NAT and its connection table
Calling out from a private subnet, and why nothing can call in

Solve it

The app in a private subnet times out calling an external API

A Spring Boot service in a private subnet must call a payment provider at https://api.payments.example. Every call times out after 30 seconds, while calls to PostgreSQL in the same VPC work. A colleague proposes opening outbound security group rules to everything and moving the instances to a public subnet. Find the cause, and fix it without exposing the instances.

  1. Read the symptom. A timeout, not “connection refused”, means packets go nowhere: a missing route or a dropping firewall. Database calls work, so DNS (Domain Name System) and the instance are fine; only the path out is broken.
  2. Check the private route table. It has only the local route for 10.0.0.0/16; nothing sends 0.0.0.0/0 anywhere. A private subnet needs a route to a NAT gateway to reach the internet.
  3. Check where the NAT gateway lives. It must sit in a public subnet, whose own route goes to the internet gateway. A NAT gateway in a private subnet has no way out either, a common mistake.
  4. Reject the shortcut. A public subnet would give the instances public reach, and their protection would rest on one security group rule. Keep them private; add the NAT route, and allow egress only to port 443.
  5. Check. From the instance, curl the provider and checkip both answer, and the IP the provider sees is the NAT gateway’s Elastic IP, which you can give it for an allowlist.
resource "aws_route" "app_to_nat" {
  route_table_id         = aws_route_table.private.id
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = aws_nat_gateway.a.id # the NAT gateway sits in public_a
}

resource "aws_vpc_security_group_egress_rule" "app_https_out" {
  security_group_id = aws_security_group.app.id
  cidr_ipv4         = "0.0.0.0/0"
  from_port         = 443
  to_port           = 443
  ip_protocol       = "tcp"
}
The missing route, plus egress limited to HTTPS

How to answer

  • Spread every tier over at least two zones for availability.
  • Choose a range that will not overlap other VPCs or offices you may connect later.
  • Reach managed services privately with VPC endpoints instead of over the internet.
  • Peering or a transit gateway connects VPCs; a VPN connects offices.

Common mistakes

  • Putting application or database instances in public subnets with public IPs.
  • Opening a database port to 0.0.0.0/0 and relying on its password.

Follow-up questions

What makes a subnet public or private?

Only its route table. A public subnet has a route for 0.0.0.0/0 to an internet gateway, so resources in it with a public IP can be reached from the internet and reach it directly. A private subnet has no such route: its resources have only private addresses, and to call out they route through a NAT (network address translation) gateway, which sits in a public subnet and lets replies back in but never new inbound connections.

  • Public is a routing property, not a firewall setting.
  • NAT gateways are per zone and cost money per hour and per gigabyte; endpoints can save traffic.
  • An ALB (Application Load Balancer) faces the internet and terminates TLS (Transport Layer Security), so the instances do not have to.

See it in the infographic: From the internet to a private service

What is a security group, and how does it differ from a network ACL?

A security group is a stateful firewall attached to each network interface: you write allow rules only, and replies to an allowed connection are let back in automatically. Rules can name another security group as the source, such as "5432 from the app group", so they follow instances as they scale. A network ACL (access control list) is stateless and applies to a whole subnet, with numbered allow and deny rules and both directions written out, including ephemeral reply ports.

  • Most designs rely on security groups and leave ACLs at their default.
  • Reference groups instead of IP ranges between tiers.
  • Default to deny inbound; open only the ports a caller needs.

See it in the infographic: From the internet to a private service

How does an app in a private subnet reach the internet and managed services such as S3 or a secrets store?

For the internet, through a NAT gateway in a public subnet: the private route table sends 0.0.0.0/0 to it, and the external service sees the NAT's public IP, which is handy for allowlists. For managed services such as S3 (Simple Storage Service) or Secrets Manager, through VPC endpoints: traffic stays on the provider's network, needs no NAT, avoids its data charges and can be limited with an endpoint policy.

  • Gateway endpoints for S3 and DynamoDB are free; interface endpoints cost per hour.
  • Without a route out, a private subnet cannot reach a managed API at all.
  • Keep egress rules narrow, such as port 443 only.

See it in the infographic: From the internet to a private service

Two VPCs both use 10.0.0.0/16. What breaks when you try to connect them?

Peering and transit gateways refuse overlapping ranges, because a route to 10.0.1.5 would be ambiguous. You must renumber one VPC, which means rebuilding its subnets and resources, or put NAT or PrivateLink in between and expose only specific services. Plan non-overlapping CIDR (Classless Inter-Domain Routing) ranges for every network up front.

Check yourself

1. Two subnets in the same VPC have identical security groups. One is public, the other private. What is different?
Show answers
  • The route table, which sends 0.0.0.0/0 to an internet gateway in one of them: Correct. Public or private is decided by routing alone.
  • A public flag set when the subnet was created: Incorrect. There is no such switch; the route defines it.
  • The public one uses a public address range: Incorrect. Both use private ranges from the VPC's block.
2. Which inbound rule should protect a PostgreSQL database used by an auto-scaling group of app instances?
Show answers
  • Port 5432 from the app instances' security group: Correct. It follows the instances as they come and go, and admits nothing else.
  • Port 5432 from 0.0.0.0/0, protected by a strong password: Incorrect. It exposes the database to every scanner on the internet.
  • Port 5432 from each app instance's IP address: Incorrect. The addresses change with every scale-out and replacement.