# VPC: your own private network

Build a real VPC with public and private subnets in two AZs, read its route tables, and see how internet gateways, NAT, security groups, network ACLs and endpoints fit together.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 4. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/04-vpc

## What you will learn

- Plan a VPC's CIDR block and split it into subnets
- Explain what makes a subnet public or private, by reading its route table
- Create a two-AZ VPC with the console wizard and read its resource map
- Know when you need a NAT gateway, and what it costs
- Tell security groups (stateful) from network ACLs (stateless)
- Use a gateway endpoint for S3, and know peering, Transit Gateway and Flow Logs

## Why a network of your own

In lesson 3 the server landed in the default VPC, where the default subnets can assign public addresses. That
is convenient for a first test, but a database should not accept connections directly from the internet. Teams
need a network plan that separates public entry points from private application and data resources.

A **Virtual Private Cloud (VPC)** is an isolated network address space in one AWS Region. You choose its IP
range, divide it into subnets in Availability Zones, and attach route tables and gateways to control paths.
The route table and resource settings determine reachability; the word "private" in VPC does not automatically
make every resource private.

This lesson builds two public and two private subnets across two Availability Zones. A public load balancer
uses the public subnets; app servers and databases belong in the private ones. You'll trace the route tables
and see how a gateway endpoint can reach S3 without general internet access.

The target for this lesson, built in a real account and deleted afterwards:

| Subnet    | AZ          | Range         | Can the internet reach it?        |
| --------- | ----------- | ------------- | --------------------------------- |
| public 1  | ap-south-1a | 10.0.0.0/20   | yes, through the internet gateway |
| public 2  | ap-south-1b | 10.0.16.0/20  | yes                               |
| private 1 | ap-south-1a | 10.0.128.0/20 | no                                |
| private 2 | ap-south-1b | 10.0.144.0/20 | no                                |

Load balancers go in the public subnets; app servers and databases in the private ones (lesson 5 uses this).

## Plan the addresses

Before creating subnets, choose address ranges that do not overlap with each other or with networks that must
connect later. Otherwise a router cannot tell which network owns an address, and a VPN or peering connection
may fail even when both sides look healthy.

A **CIDR block** is a range written as a network address and a prefix length. The prefix says how many bits
identify the network; the remaining bits identify addresses inside it. A smaller prefix number leaves more
host bits and therefore more addresses. AWS reserves five addresses in each IPv4 subnet, so the number of
usable addresses is lower than the raw range size.

The table gives the raw address counts:

| CIDR          | Addresses | Typical use                          |
| ------------- | --------- | ------------------------------------ |
| `10.0.0.0/16` | 65,536    | a whole VPC (the largest AWS allows) |
| `10.0.0.0/20` | 4,096     | one subnet                           |
| `10.0.0.0/24` | 256       | a small subnet                       |

AWS reserves 5 addresses in every subnet (the first four and the last), so a /24 gives 251 usable. Use the
private ranges `10.0.0.0/8`, `172.16.0.0/12` or `192.168.0.0/16`, and give every VPC a range that doesn't
overlap the others or your office network, or you can never connect them later.

Here the VPC uses `10.0.0.0/16`, and each subnet gets a `/20` slice. This leaves room for multiple subnets
while keeping each one large enough for the demo. In production, plan for expected growth and every connected
network before creating the VPC; changing address plans later can require replacing resources. A common
mistake is assigning the same RFC 1918 range to both sides of a VPN and expecting routes to distinguish them.

## Subnets in two AZs

**Why two Availability Zones?** An AZ is one or more data centres in a region. Now and then one has a
power or network problem. If all your servers sit in one AZ, that problem takes your whole app down.
Put them in two AZs and the other one keeps serving. So every layer of a production network comes in
pairs: a subnet in each AZ, and servers spread across both.

**Public or private subnet?** A subnet doesn't have a "public" switch. What makes it public is its
**route table**: if it has a route to an **internet gateway**, machines in it with a public IP can be
reached from the internet. A private subnet has no such route. Its machines can still reach out (to
download updates) through a **NAT gateway**, but nobody on the internet can connect in. Load balancers
go in public subnets. App servers and databases go in private ones.

> **Figure.** academy-vpc, 10.0.0.0/16 in ap-south-1, spans two Availability Zones. Each zone has a public subnet with a load balancer and a route 0.0.0.0/0 to the internet gateway academy-igw, and a private subnet with an app server whose default route goes to an optional NAT gateway or nowhere. An S3 gateway endpoint lets private servers reach S3 without the internet.
>
> Public subnets have a route to the internet gateway. Private subnets don't, so the internet can't reach the app servers.

**VPC → Your VPCs → Create VPC → VPC and more** builds the whole network in one go, and draws it as you type:

> **Figure.** Create VPC page. (1) VPC and more selected instead of VPC only. (2) Name tag auto-generation: academy. (3) IPv4 CIDR block 10.0.0.0/16, 65,536 IPs. The Preview on the right draws academy-vpc, four subnets across ap-south-1a and ap-south-1b, and route tables.
>
> (1) VPC and more. (2) A name prefix for everything it creates. (3) The VPC's address range.

> **Figure.** Further down the form: (1) 2 Availability Zones, (2) 2 public subnets, (3) 2 private subnets, (4) NAT gateways None, with Regional and Zonal options marked as costing money, (5) VPC endpoints: S3 Gateway. DNS hostnames and resolution enabled. The preview shows the public and private route tables.
>
> (1–3) Two AZs, each with a public and a private subnet. (4) No NAT gateway: it costs money by the hour. (5) A free S3 gateway endpoint.

> **Figure.** Create VPC workflow page listing each step completed: VPC, DNS settings, subnets, internet gateway attached, route tables created and associated, routes added, and the S3 endpoint, with a View VPC button.
>
> Everything the wizard did for you, step by step. Each of these is one API call you could also script.

The VPC's **Resource map** tab shows how the pieces connect:

> **Figure.** academy-vpc details and Resource map: (1) four subnets, public1 and private1 in ap-south-1a, public2 and private2 in ap-south-1b; (2) route tables academy-rtb-public, academy-rtb-private1, academy-rtb-private2 and the main table; (3) network connections academy-igw and academy-vpce-s3, linked by lines.
>
> (1) Subnets → (2) their route tables → (3) where traffic can leave: the internet gateway or the S3 endpoint.

> **Figure.** Subnets list filtered to academy-vpc: four subnets with their IPv4 CIDRs, available IP counts and Availability Zones, with the 10.0.0.0/20 and 10.0.128.0/20 ranges highlighted.
>
> (1) A public subnet's range. (2) A private one. Same size, different route tables.

## What makes a subnet public

The name "public subnet" does not come from a checkbox or from the subnet's CIDR. Its **route table** determines
where traffic can go. A route table is a set of destination ranges and next hops. When an instance sends a
packet, the VPC uses the most specific matching route to choose where it goes.

For internet access, a public subnet needs a default route (`0.0.0.0/0`) to an internet gateway. The VPC must
have that gateway attached, and an instance also needs a public IPv4 address plus a security group that allows
the intended inbound traffic. A route alone does not make the instance reachable.

The screenshots contrast the public route table with a private one:

> **Figure.** Route table academy-rtb-public, associated with 2 subnets. Routes: 0.0.0.0/0 to igw-076e67d884dd9f303, and 10.0.0.0/16 to local, both Active.
>
> The public route table: 0.0.0.0/0 (everything not local) goes to the internet gateway.

> **Figure.** Route table academy-rtb-private1: a route for the S3 prefix list to the VPC endpoint, and 10.0.0.0/16 to local. There is no 0.0.0.0/0 route.
>
> A private route table: only local traffic and S3 through the endpoint. No route to the internet at all.

| Route                 | Means                                                               |
| --------------------- | ------------------------------------------------------------------- |
| `10.0.0.0/16 → local` | in every route table: any subnet can reach any other inside the VPC |
| `0.0.0.0/0 → igw-…`   | the **internet gateway**: makes the subnet public, both directions  |
| `pl-… → vpce-…`       | S3 through the gateway endpoint, without the internet               |

An instance in a public subnet also needs a **public IP** to be reachable; one in a private subnet has only a
private address, and nothing outside the VPC can start a connection to it.

Use public subnets for internet-facing load balancers and private subnets for application servers and
databases. Keep private routes private unless the workload needs outbound access. A common mistake is to add
an internet-gateway route and assume that is sufficient; confirm address assignment and security-group rules
as well.

## NAT: the way out for private subnets

Private servers may need to download operating-system updates or call an external API, but they should not
accept unsolicited connections from the internet. A **Network Address Translation (NAT) gateway** lets
instances initiate outbound IPv4 connections while hiding their private source addresses behind a public
address. It sits in a public subnet; a private subnet's default route points to it.

The packet leaves the private instance, follows `0.0.0.0/0 → nat-…`, and reaches the NAT gateway. The gateway
rewrites the source address for the outbound connection and tracks the reply so it can send the response back
to the instance. It does not create an inbound path for a new internet connection. NAT gateways are zonal or
regional options in the VPC wizard; their availability and pricing differ, so check current AWS details before
choosing.

> **NAT gateways cost money even when idle.** A NAT gateway is billed per hour and per GB processed, plus its public IPv4 address: tens of dollars a month for one sitting idle. That's why the wizard defaults to None and this lesson didn't create one. For learning, skip it; in production, size it on purpose, and use gateway endpoints for S3 and DynamoDB traffic.

Use a NAT gateway when private workloads need general outbound internet access and the cost is justified.
For AWS services such as S3 and DynamoDB, a gateway VPC endpoint may avoid routing that traffic through NAT.
For a small lab that needs no outbound access, choose **None**. A common mistake is creating one NAT gateway
per AZ for a tutorial and forgetting that each gateway has an hourly charge.

> **Video.** [How do I set up a NAT gateway for a private subnet in Amazon VPC?](https://www.youtube.com/watch?v=26hx-egrMLw) (Amazon Web Services)

## Two firewalls

|             | Security group                                      | Network ACL                                    |
| ----------- | --------------------------------------------------- | ---------------------------------------------- |
| Attached to | an instance (its network interface)                 | a subnet                                       |
| State       | **stateful**: a reply to allowed traffic is allowed | **stateless**: rules needed in both directions |
| Rules       | allow only                                          | allow and deny, evaluated in number order      |
| Default     | nothing in, everything out                          | the default ACL allows everything              |

> **Figure.** The default network ACL of academy-vpc, inbound rules: rule 100 all traffic from 0.0.0.0/0 Allow, and rule * all traffic Deny.
>
> (1) Rule 100 allows everything. (2) The * rule denies whatever no numbered rule matched.

> **Figure.** The default security group of academy-vpc with its Inbound rules tab: one rule allowing all traffic from members of the same security group.
>
> A VPC's default security group only lets in traffic from other members of itself.

**Stateful or stateless, in practice.** Your server sends a request to an update server on port 443.
The reply comes back to a random high port on your server (say 49731). A **security group** remembers
the outgoing request, so it lets the reply in without any extra rule. A **network ACL** remembers
nothing: it checks the reply like any other incoming packet, so you'd need an inbound rule allowing
the whole range of those high ports (1024–65535). That's why ACLs are easy to get wrong.

Most teams leave network ACLs at their defaults and filter with security groups, because a security group can
name another security group as the source ("only from the load balancer"), which lesson 5 uses.

## Endpoints, peering and flow logs

- **Gateway endpoints** (S3 and DynamoDB only) add a route, cost nothing, and keep that traffic off the NAT
  gateway. The wizard created one: `academy-vpce-s3`.
- **Interface endpoints** (PrivateLink) put a private IP for an AWS service (ECR, Secrets Manager, SSM) inside
  your subnet. They cost per hour, and they let private subnets work with no internet access at all.
- **VPC peering** connects two VPCs one-to-one; ranges must not overlap. **Transit Gateway** is a hub for many
  VPCs and VPN connections, when peering every pair gets out of hand.
- **VPC Flow Logs** record accepted and rejected connections per interface, to CloudWatch Logs or S3: the first
  thing to turn on when "the network is blocking it" (lesson 13).

## Clean up

Delete the VPC from **Your VPCs → Actions → Delete VPC**; the console deletes its subnets, route tables, internet
gateway and endpoint with it. From the CLI you delete them yourself, in order:

```sh
$ aws ec2 delete-vpc-endpoints --vpc-endpoint-ids vpce-…
$ aws ec2 detach-internet-gateway --internet-gateway-id igw-… --vpc-id vpc-…
$ aws ec2 delete-internet-gateway --internet-gateway-id igw-…
$ aws ec2 delete-subnet --subnet-id subnet-…                 # each of the four
$ aws ec2 delete-route-table --route-table-id rtb-…          # each non-main table
$ aws ec2 delete-vpc --vpc-id vpc-…
```

> **In production.** Plan non-overlapping CIDRs for every VPC and environment up front, use at least two AZs, keep databases and app servers in private subnets, give each team or environment its own VPC (or account), turn on Flow Logs, and build it all with Terraform or CloudFormation (lesson 16) rather than the wizard.

## Mission: Build and read a two-tier network

Create a VPC with 2 AZs, 2 public and 2 private subnets, no NAT gateway and an S3 gateway endpoint. Prove from the route tables which subnets are public, then delete the whole VPC and confirm it's gone.

- You need: An AWS account with the console and AWS CLI
- You'll have: Route tables showing 0.0.0.0/0 to an internet gateway only for the public subnets, then no academy-vpc left

```sh
$ # 1. Console: VPC → Create VPC → VPC and more, name academy, 10.0.0.0/16, 2 AZs, 2 public, 2 private,
$ #    NAT None, S3 Gateway → Create VPC
$ V=$(aws ec2 describe-vpcs --filters Name=tag:Name,Values=academy-vpc --query 'Vpcs[0].VpcId' --output text)
$ aws ec2 describe-route-tables --filters Name=vpc-id,Values=$V \
    --query 'RouteTables[].[Tags[?Key==`Name`]|[0].Value, Routes[?DestinationCidrBlock==`0.0.0.0/0`]|[0].GatewayId]' --output text
$ # 2. Console: Your VPCs → select academy-vpc → Actions → Delete VPC → type delete
$ aws ec2 describe-vpcs --filters Name=tag:Name,Values=academy-vpc --query 'length(Vpcs)'   # 0 when it's gone
```

Expect one line per route table: only `academy-rtb-public` shows an `igw-…` ID; the private tables and the
main table show `None`, because they have no route to the internet. Without a
NAT gateway this network costs nothing, so you can rebuild it whenever you like.

## Try it

- Create a VPC with the VPC and more wizard, 2 AZs, NAT None and the S3 gateway endpoint.
- Open the VPC's Resource map tab and trace a public subnet to the internet gateway.
- Compare the public and private route tables. Which route is missing from the private one?
- Read the default network ACL rules and explain the rule numbered with a star.
- Work out how many IP addresses a /20 subnet has, and how many you can actually use.
- Delete the VPC and everything in it, then check nothing is left.

## Quiz

1. What makes a subnet public?
   - Its name contains public
   - **Its route table has a route 0.0.0.0/0 to an internet gateway** (answer)
   - It has more IP addresses
   Why: Public and private are just route tables. The private ones have only the local route (and endpoints), so the internet can't reach them and they can't reach it.

2. Servers in a private subnet need to download updates. What gives them outbound internet access without being reachable from it?
   - An internet gateway route
   - **A NAT gateway in a public subnet, with the private route table pointing 0.0.0.0/0 at it** (answer)
   - A security group rule
   Why: NAT lets traffic out and replies back in, but nothing can start a connection from outside. It costs money per hour and per GB, so the wizard defaults to None.

3. Security group vs network ACL: which statement is true?
   - Both are stateless
   - **Security groups are stateful and attach to instances; network ACLs are stateless, attach to subnets and need rules for both directions** (answer)
   - Network ACLs can only allow
   Why: The default ACL allows everything, and its last rule (*) denies anything not matched. Most teams keep ACLs default and do their filtering with security groups.

4. Your VPC is 10.0.0.0/16. How many addresses can a /20 subnet hold?
   - 16
   - **4,096, of which 4,091 usable (AWS reserves 5 in every subnet)** (answer)
   - 65,536
   Why: 32 - 20 = 12 bits, 2^12 = 4,096. The first four and the last address of each subnet are reserved.

5. Instances in a private subnet read from S3 a lot. How do you avoid paying NAT data charges for it?
   - Make the subnet public
   - **Add an S3 gateway endpoint, which puts an S3 route in the route table at no extra cost** (answer)
   - Use a bigger NAT gateway
   Why: The wizard's S3 Gateway option did exactly that; you could see the prefix-list route in the private route table.

## Resources

- [How Amazon VPC works](https://docs.aws.amazon.com/vpc/latest/userguide/how-it-works.html) (AWS Docs)
- [Subnet CIDR blocks](https://docs.aws.amazon.com/vpc/latest/userguide/subnet-sizing.html) (AWS Docs)
- [NAT gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) (AWS Docs)
- [Compare security groups and network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/infrastructure-security.html) (AWS Docs)
- [VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html) (AWS Docs)
