Skip to content

Before the First Server: Designing a Production Ready AWS VPC from Scratch with Terraform

Build a production ready AWS VPC with Terraform, covering multi-AZ subnets, route tables, NAT and internet gateways, security groups, NACLs, VPC endpoints, and flow logs.

Author
Navinda Chandrasiri
Published
Reading time
20 min read
Topics
AWSVPCTerraformNetworkingNAT GatewayVPC EndpointsSecurity GroupsNACLInfrastructure as CodeCloud Architecture
Before the First Server: Designing a Production Ready AWS VPC from Scratch with Terraform
On this page

Every AWS workload you will ever run sits on top of a network. Get the network right and everything above it, from load balancers to databases to Kubernetes clusters, becomes easier to secure, cheaper to run, and simpler to reason about. Get it wrong and you will be fighting it for years, because some VPC decisions (like the CIDR range) are painful to change once real traffic is flowing.

In this post we will design and build a production grade VPC from scratch using Terraform. We will cover:

  • A multi-AZ, three tier subnet layout with a deliberate CIDR plan
  • Internet gateway, NAT gateways, and route tables
  • Gateway and interface VPC endpoints
  • Security groups for a classic ALB, application, and database stack
  • Network ACLs as a second layer of defence
  • VPC flow logs for visibility

And because these two questions come up in every architecture review, we will answer them properly, with the reasoning and not just the rules of thumb:

  1. NAT Gateways vs VPC endpoints: when do you use which?
  2. Security groups vs network ACLs: do you need both?

Design Principles#

Before writing any Terraform, it helps to agree on what "production ready" means. Here are the principles behind every decision in this post:

  1. Highly available. Spread across three Availability Zones, with one NAT gateway per AZ, so losing a whole AZ never takes down egress for the others.
  2. Private by default. Only load balancers and NAT gateways live in public subnets. Applications and databases have no public IPs.
  3. Tiered. Public, private (application), and data tiers, each with its own route table and network ACL.
  4. Least privilege. Security groups reference each other instead of broad CIDR ranges, and the default security group is locked down to nothing.
  5. Cost aware. Gateway endpoints for S3 and DynamoDB (they are free), interface endpoints only for the services that justify them, and a single-NAT toggle for non-production environments.
  6. Observable. Flow logs are on from day one, because you cannot debug or audit traffic you did not record.
  7. Everything as code. Reviewed in pull requests, reproducible in any account or region.

The Architecture#

Architecture diagram: Producton ready AWS VPC network architecture.

Here is how traffic moves through it:

  • Inbound from the internet: Internet gateway → ALB in a public subnet → application targets in a private subnet → database in the data tier
  • Outbound to the internet: Application in a private subnet → NAT gateway in the same AZ → internet gateway
  • To AWS services: Application → gateway endpoint (S3, DynamoDB) or interface endpoint (ECR, CloudWatch Logs, Secrets Manager, and so on), never leaving the AWS network
  • Data tier: Reachable only from the application tier. It has no default route, so there is no path to or from the internet

Planning the CIDR Ranges#

This is the one step you cannot casually redo, so spend a minute on it.

We use 10.0.0.0/16, which gives 65,536 addresses. Three rules of thumb guided the layout:

  • Do not overlap with any other VPC, on-premises network, or VPN range you might ever need to connect to. Overlapping CIDRs cannot be peered or routed. In a real organization, take your range from a central plan (AWS IPAM is built for this).
  • Give the application tier the most room. Container platforms like EKS and ECS can consume a lot of IPs, so each private subnet is a /20 (4,091 usable addresses).
  • Keep public and data subnets small. They hold few resources, so a /24 (251 usable addresses) is plenty. AWS reserves five addresses in every subnet.

The resulting plan:

  • Public: 10.0.0.0/24, 10.0.1.0/24, 10.0.2.0/24
  • Data: 10.0.10.0/24, 10.0.11.0/24, 10.0.12.0/24
  • Private (application): 10.0.16.0/20, 10.0.32.0/20, 10.0.48.0/20
  • Unused and reserved for growth: everything from 10.0.64.0/18 upward, plus the gaps in between

Terraform's cidrsubnet() function calculates these for us, so there are no hand-typed subnet ranges to get wrong.

Prerequisites#

  • An AWS account and the AWS CLI configured locally
  • Terraform 1.6 or newer
  • Basic familiarity with Terraform and AWS networking concepts

Project Layout#

text
vpc/
├── providers.tf
├── variables.tf
├── locals.tf
├── vpc.tf
├── nat.tf
├── endpoints.tf
├── security-groups.tf
├── nacls.tf
├── flow-logs.tf
└── outputs.tf

Once it works, this layout converts neatly into a reusable module. Keep it flat for now so every resource is easy to find while you learn.

Step 1: Providers, Variables, and Locals#

hcl
# vpc/providers.tf
terraform {
  required_version = ">= 1.6"
 
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}
 
provider "aws" {
  region = var.region
 
  # Every resource gets these tags automatically
  default_tags {
    tags = {
      Project     = var.name
      Environment = var.environment
      ManagedBy   = "terraform"
    }
  }
}
hcl
# vpc/variables.tf
variable "region" {
  type    = string
  default = "ap-southeast-1"
}
 
variable "name" {
  type        = string
  description = "Name prefix for all resources"
  default     = "prod"
}
 
variable "environment" {
  type    = string
  default = "production"
}
 
variable "vpc_cidr" {
  type        = string
  description = "Primary VPC CIDR. The subnet maths below assumes a /16."
  default     = "10.0.0.0/16"
}
 
variable "az_count" {
  type        = number
  description = "Number of Availability Zones to use"
  default     = 3
 
  validation {
    condition     = var.az_count >= 2 && var.az_count <= 3
    error_message = "az_count must be 2 or 3."
  }
}
 
variable "single_nat_gateway" {
  type        = bool
  description = "Use one shared NAT gateway. Cheaper, but not highly available. Intended for dev and staging only."
  default     = false
}
 
variable "app_port" {
  type    = number
  default = 8080
}
 
variable "db_port" {
  type    = number
  default = 5432
}
hcl
# vpc/locals.tf
data "aws_availability_zones" "available" {
  state = "available"
 
  filter {
    name   = "opt-in-status"
    values = ["opt-in-not-required"]
  }
}
 
locals {
  azs = slice(data.aws_availability_zones.available.names, 0, var.az_count)
 
  # Maps of AZ name => subnet CIDR
  public_subnets  = { for i, az in local.azs : az => cidrsubnet(var.vpc_cidr, 8, i) }      # /24
  data_subnets    = { for i, az in local.azs : az => cidrsubnet(var.vpc_cidr, 8, i + 10) } # /24
  private_subnets = { for i, az in local.azs : az => cidrsubnet(var.vpc_cidr, 4, i + 1) }  # /20
 
  nat_count = var.single_nat_gateway ? 1 : var.az_count
}

Keying the subnet maps by AZ name is a small trick with a big payoff: later resources can say "the private route table for this AZ" with a simple lookup, without juggling list indexes.

Step 2: The VPC, Internet Gateway, and Subnets#

hcl
# vpc/vpc.tf
resource "aws_vpc" "this" {
  cidr_block           = var.vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true # required for interface endpoint private DNS
 
  tags = { Name = "${var.name}-vpc" }
}
 
resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id
 
  tags = { Name = "${var.name}-igw" }
}
 
resource "aws_subnet" "public" {
  for_each = local.public_subnets
 
  vpc_id            = aws_vpc.this.id
  availability_zone = each.key
  cidr_block        = each.value
 
  # Nothing is public by accident. Load balancers and NAT gateways get
  # their public addresses explicitly.
  map_public_ip_on_launch = false
 
  tags = {
    Name = "${var.name}-public-${each.key}"
    Tier = "public"
  }
}
 
resource "aws_subnet" "private" {
  for_each = local.private_subnets
 
  vpc_id            = aws_vpc.this.id
  availability_zone = each.key
  cidr_block        = each.value
 
  tags = {
    Name = "${var.name}-private-${each.key}"
    Tier = "private"
  }
}
 
resource "aws_subnet" "data" {
  for_each = local.data_subnets
 
  vpc_id            = aws_vpc.this.id
  availability_zone = each.key
  cidr_block        = each.value
 
  tags = {
    Name = "${var.name}-data-${each.key}"
    Tier = "data"
  }
}
 
# The default security group is locked down: no rules means no traffic.
# Nothing should ever rely on it.
resource "aws_default_security_group" "default" {
  vpc_id = aws_vpc.this.id
 
  tags = { Name = "${var.name}-default-sg-do-not-use" }
}

A note on map_public_ip_on_launch = false: some tutorials turn this on for public subnets. In production I prefer the opposite. Instances you launch into a public subnet should not silently get a public IP, and the resources that really need one (NAT gateways, internet-facing load balancers) get theirs through other mechanisms.

If you plan to run EKS later, this is also the place to add the subnet discovery tags, kubernetes.io/role/elb on public subnets and kubernetes.io/role/internal-elb on private ones.

Step 3: NAT Gateways and Route Tables#

Each NAT gateway needs an Elastic IP and must sit in a public subnet. Then every private subnet gets its own route table pointing at the NAT gateway in its own AZ:

hcl
# vpc/nat.tf
resource "aws_eip" "nat" {
  count  = local.nat_count
  domain = "vpc"
 
  tags = { Name = "${var.name}-nat-eip-${count.index + 1}" }
 
  depends_on = [aws_internet_gateway.this]
}
 
resource "aws_nat_gateway" "this" {
  count = local.nat_count
 
  allocation_id = aws_eip.nat[count.index].id
  subnet_id     = aws_subnet.public[local.azs[count.index]].id
 
  tags = { Name = "${var.name}-nat-${local.azs[count.index]}" }
 
  depends_on = [aws_internet_gateway.this]
}
 
# ---------- Public: default route to the internet gateway ----------
resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id
 
  tags = { Name = "${var.name}-public-rt" }
}
 
resource "aws_route" "public_internet" {
  route_table_id         = aws_route_table.public.id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = aws_internet_gateway.this.id
}
 
resource "aws_route_table_association" "public" {
  for_each = aws_subnet.public
 
  subnet_id      = each.value.id
  route_table_id = aws_route_table.public.id
}
 
# ---------- Private: one route table per AZ, default route to that AZ's NAT ----------
resource "aws_route_table" "private" {
  for_each = local.private_subnets
 
  vpc_id = aws_vpc.this.id
 
  tags = { Name = "${var.name}-private-rt-${each.key}" }
}
 
resource "aws_route" "private_nat" {
  for_each = aws_route_table.private
 
  route_table_id         = each.value.id
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = aws_nat_gateway.this[var.single_nat_gateway ? 0 : index(local.azs, each.key)].id
}
 
resource "aws_route_table_association" "private" {
  for_each = aws_subnet.private
 
  subnet_id      = each.value.id
  route_table_id = aws_route_table.private[each.key].id
}
 
# ---------- Data: no default route. Local VPC traffic only. ----------
resource "aws_route_table" "data" {
  vpc_id = aws_vpc.this.id
 
  tags = { Name = "${var.name}-data-rt" }
}
 
resource "aws_route_table_association" "data" {
  for_each = aws_subnet.data
 
  subnet_id      = each.value.id
  route_table_id = aws_route_table.data.id
}

Three details here are worth pausing on:

  • One NAT gateway per AZ. A NAT gateway is zonal. If it lives in AZ-a and AZ-a fails, every private subnet pointing at it loses internet access. With one per AZ, a failure stays contained. It also avoids cross-AZ data transfer charges for traffic that would otherwise hop between zones to reach a shared NAT.
  • A separate private route table per AZ. That is what lets each AZ point at its own NAT gateway.
  • The data route table has no 0.0.0.0/0 route. It only contains the implicit local route, so databases cannot reach the internet and the internet cannot reach them, even if someone makes a security group mistake later. The route table itself is a guardrail.

Step 4: VPC Endpoints#

Endpoints let your resources talk to AWS services without going through the NAT gateway and the public internet. There are two kinds, and they work very differently:

  • Gateway endpoints (S3 and DynamoDB only) add routes to your route tables. They are free.
  • Interface endpoints (most other services) place elastic network interfaces, powered by AWS PrivateLink, inside your subnets. They cost per hour per AZ plus per GB.
hcl
# vpc/endpoints.tf
locals {
  gateway_endpoints = toset(["s3", "dynamodb"])
 
  # Trim this list to the services you actually use. Each one costs money in every AZ.
  interface_endpoints = toset([
    "ecr.api",        # ECR control plane
    "ecr.dkr",        # ECR Docker registry
    "logs",           # CloudWatch Logs
    "sts",            # IAM role credentials
    "secretsmanager", # Secrets Manager
    "ssm",            # Systems Manager
    "ssmmessages",    # Session Manager
    "ec2messages",    # Systems Manager agent
  ])
}
 
# ---------- Gateway endpoints: free, route-table based ----------
resource "aws_vpc_endpoint" "gateway" {
  for_each = local.gateway_endpoints
 
  vpc_id            = aws_vpc.this.id
  service_name      = "com.amazonaws.${var.region}.${each.key}"
  vpc_endpoint_type = "Gateway"
 
  route_table_ids = concat(
    [for rt in aws_route_table.private : rt.id],
    [aws_route_table.data.id]
  )
 
  tags = { Name = "${var.name}-${each.key}-gw-endpoint" }
}
 
# ---------- Interface endpoints: PrivateLink ENIs in the private subnets ----------
resource "aws_vpc_endpoint" "interface" {
  for_each = local.interface_endpoints
 
  vpc_id              = aws_vpc.this.id
  service_name        = "com.amazonaws.${var.region}.${each.key}"
  vpc_endpoint_type   = "Interface"
  subnet_ids          = [for s in aws_subnet.private : s.id]
  security_group_ids  = [aws_security_group.endpoints.id]
  private_dns_enabled = true # the normal service hostname now resolves to the endpoint
 
  tags = { Name = "${var.name}-${each.key}-endpoint" }
}

With private_dns_enabled = true, your application code does not change at all. A call to logs.ap-southeast-1.amazonaws.com simply resolves to the private endpoint addresses instead of public ones.

One classic trap: pulling container images from ECR needs ecr.api, ecr.dkr, and the S3 gateway endpoint, because image layers are stored in S3. Skip the S3 endpoint and your pulls will hang or fall back to the NAT gateway.

Step 5: Security Groups#

Security groups are your primary access control. The golden rule is to reference other security groups instead of CIDR ranges wherever possible. "The app tier may talk to the database" survives subnet changes, autoscaling, and IP churn. "10.0.16.0/20 may talk to the database" does not.

I use the standalone rule resources (aws_vpc_security_group_ingress_rule and aws_vpc_security_group_egress_rule) rather than inline blocks. They avoid a whole category of Terraform diff problems and handle circular references between groups cleanly.

hcl
# vpc/security-groups.tf
 
# ---------- Groups ----------
resource "aws_security_group" "alb" {
  name        = "${var.name}-alb-sg"
  description = "Public ALB: web traffic from the internet"
  vpc_id      = aws_vpc.this.id
 
  tags = { Name = "${var.name}-alb-sg" }
}
 
resource "aws_security_group" "app" {
  name        = "${var.name}-app-sg"
  description = "Application tier: traffic only from the ALB"
  vpc_id      = aws_vpc.this.id
 
  tags = { Name = "${var.name}-app-sg" }
}
 
resource "aws_security_group" "db" {
  name        = "${var.name}-db-sg"
  description = "Database tier: traffic only from the application tier"
  vpc_id      = aws_vpc.this.id
 
  tags = { Name = "${var.name}-db-sg" }
}
 
# No egress rules are defined, so Terraform removes the default allow-all egress
resource "aws_security_group" "endpoints" {
  name        = "${var.name}-endpoints-sg"
  description = "Interface endpoints: HTTPS from inside the VPC"
  vpc_id      = aws_vpc.this.id
 
  tags = { Name = "${var.name}-endpoints-sg" }
}
 
# ---------- ALB ----------
resource "aws_vpc_security_group_ingress_rule" "alb_https" {
  security_group_id = aws_security_group.alb.id
  description       = "HTTPS from the internet"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}
 
resource "aws_vpc_security_group_ingress_rule" "alb_http" {
  security_group_id = aws_security_group.alb.id
  description       = "HTTP from the internet (redirected to HTTPS by the listener)"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 80
  to_port           = 80
}
 
resource "aws_vpc_security_group_egress_rule" "alb_to_app" {
  security_group_id            = aws_security_group.alb.id
  description                  = "To the application tier"
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = var.app_port
  to_port                      = var.app_port
}
 
# ---------- Application ----------
resource "aws_vpc_security_group_ingress_rule" "app_from_alb" {
  security_group_id            = aws_security_group.app.id
  description                  = "From the ALB"
  referenced_security_group_id = aws_security_group.alb.id
  ip_protocol                  = "tcp"
  from_port                    = var.app_port
  to_port                      = var.app_port
}
 
resource "aws_vpc_security_group_egress_rule" "app_to_db" {
  security_group_id            = aws_security_group.app.id
  description                  = "To the database"
  referenced_security_group_id = aws_security_group.db.id
  ip_protocol                  = "tcp"
  from_port                    = var.db_port
  to_port                      = var.db_port
}
 
resource "aws_vpc_security_group_egress_rule" "app_https_out" {
  security_group_id = aws_security_group.app.id
  description       = "HTTPS to AWS endpoints, S3, and the internet through NAT"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}
 
# ---------- Database ----------
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  description                  = "From the application tier"
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = var.db_port
  to_port                      = var.db_port
}
 
# ---------- Interface endpoints ----------
resource "aws_vpc_security_group_ingress_rule" "endpoints_https" {
  security_group_id = aws_security_group.endpoints.id
  description       = "HTTPS from inside the VPC"
  cidr_ipv4         = aws_vpc.this.cidr_block
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

Notice what is absent: the database security group has no egress rules at all, the ALB can only send traffic to the app tier, and the app tier can only reach the database and port 443. If an application server is ever compromised, its ability to move laterally or exfiltrate data over odd ports is already restricted by default. For even tighter control, replace the app tier's 0.0.0.0/0 HTTPS egress with specific destinations such as the S3 managed prefix list.

Step 6: Network ACLs#

Network ACLs (NACLs) are stateless and sit at the subnet boundary. That statelessness is the thing to respect: because return traffic is not automatically allowed, every NACL needs explicit rules for the ephemeral ports (1024 to 65535) used by replies.

I build the rules as a data structure and create them with a single for_each. It keeps the rule tables readable and makes the whole policy easy to review at a glance:

hcl
# vpc/nacls.tf
locals {
  eph_from = 1024
  eph_to   = 65535
  anywhere = "0.0.0.0/0"
 
  # ---------- Public tier: ALB and NAT gateways ----------
  public_nacl_rules = {
    public_in_https  = { nacl = "public", rule = 100, egress = false, proto = "tcp", cidr = local.anywhere, from = 443, to = 443 }
    public_in_http   = { nacl = "public", rule = 110, egress = false, proto = "tcp", cidr = local.anywhere, from = 80, to = 80 }
    public_in_return = { nacl = "public", rule = 120, egress = false, proto = "tcp", cidr = local.anywhere, from = local.eph_from, to = local.eph_to }
    public_in_vpc    = { nacl = "public", rule = 130, egress = false, proto = "-1", cidr = var.vpc_cidr, from = 0, to = 0 }
 
    public_out_https  = { nacl = "public", rule = 100, egress = true, proto = "tcp", cidr = local.anywhere, from = 443, to = 443 }
    public_out_return = { nacl = "public", rule = 110, egress = true, proto = "tcp", cidr = local.anywhere, from = local.eph_from, to = local.eph_to }
    public_out_vpc    = { nacl = "public", rule = 120, egress = true, proto = "-1", cidr = var.vpc_cidr, from = 0, to = 0 }
  }
 
  # ---------- Private tier: applications and interface endpoints ----------
  private_nacl_rules = merge(
    {
      private_in_app    = { nacl = "private", rule = 100, egress = false, proto = "tcp", cidr = var.vpc_cidr, from = var.app_port, to = var.app_port }
      private_in_https  = { nacl = "private", rule = 110, egress = false, proto = "tcp", cidr = var.vpc_cidr, from = 443, to = 443 }
      private_in_return = { nacl = "private", rule = 120, egress = false, proto = "tcp", cidr = local.anywhere, from = local.eph_from, to = local.eph_to }
 
      private_out_https  = { nacl = "private", rule = 100, egress = true, proto = "tcp", cidr = local.anywhere, from = 443, to = 443 }
      private_out_return = { nacl = "private", rule = 150, egress = true, proto = "tcp", cidr = var.vpc_cidr, from = local.eph_from, to = local.eph_to }
    },
    # Database access, but only towards the data subnets
    { for az, cidr in local.data_subnets : "private_out_db_${az}" => {
      nacl = "private", rule = 110 + index(local.azs, az), egress = true, proto = "tcp", cidr = cidr, from = var.db_port, to = var.db_port
    } }
  )
 
  # ---------- Data tier: only the private subnets may connect ----------
  data_nacl_rules = merge(
    { for az, cidr in local.private_subnets : "data_in_db_${az}" => {
      nacl = "data", rule = 100 + index(local.azs, az), egress = false, proto = "tcp", cidr = cidr, from = var.db_port, to = var.db_port
    } },
    { for az, cidr in local.private_subnets : "data_out_return_${az}" => {
      nacl = "data", rule = 100 + index(local.azs, az), egress = true, proto = "tcp", cidr = cidr, from = local.eph_from, to = local.eph_to
    } }
  )
 
  nacl_rules = merge(local.public_nacl_rules, local.private_nacl_rules, local.data_nacl_rules)
 
  nacl_ids = {
    public  = aws_network_acl.public.id
    private = aws_network_acl.private.id
    data    = aws_network_acl.data.id
  }
}
 
resource "aws_network_acl" "public" {
  vpc_id     = aws_vpc.this.id
  subnet_ids = [for s in aws_subnet.public : s.id]
 
  tags = { Name = "${var.name}-public-nacl" }
}
 
resource "aws_network_acl" "private" {
  vpc_id     = aws_vpc.this.id
  subnet_ids = [for s in aws_subnet.private : s.id]
 
  tags = { Name = "${var.name}-private-nacl" }
}
 
resource "aws_network_acl" "data" {
  vpc_id     = aws_vpc.this.id
  subnet_ids = [for s in aws_subnet.data : s.id]
 
  tags = { Name = "${var.name}-data-nacl" }
}
 
resource "aws_network_acl_rule" "this" {
  for_each = local.nacl_rules
 
  network_acl_id = local.nacl_ids[each.value.nacl]
  rule_number    = each.value.rule
  egress         = each.value.egress
  protocol       = each.value.proto
  rule_action    = "allow"
  cidr_block     = each.value.cidr
  from_port      = each.value.from
  to_port        = each.value.to
}

It is a lot of numbers, so here is the logic in plain English:

  • Public NACL: accepts web traffic from anywhere, accepts replies to outbound connections (NAT traffic heading to the internet), and talks freely with the VPC. Outbound is limited to HTTPS, replies, and the VPC.
  • Private NACL: accepts the application port and endpoint HTTPS traffic from inside the VPC, plus replies. Outbound HTTPS is allowed to anywhere (for NAT and AWS services), database traffic is only allowed towards the data subnets, and replies go back to the VPC.
  • Data NACL: the strictest of the three. It accepts only the database port from the private subnets and only sends replies back to them. Nothing else gets in or out.

A side effect worth knowing: the public NACL only allows outbound port 443 to the internet, so workloads behind the NAT gateway can only reach HTTPS destinations. That is a deliberate egress control. If you genuinely need plain HTTP or other ports outward, add explicit rules for them.

Also note that NACLs do not filter traffic to the Amazon-provided DNS resolver, DHCP, or the instance metadata service, so you do not need rules for those.

Step 7: Flow Logs#

Flow logs record accepted and rejected connections across the VPC. When someone says "the app cannot reach the database", the flow log tells you whether a security group or NACL dropped the packet.

hcl
# vpc/flow-logs.tf
resource "aws_cloudwatch_log_group" "flow" {
  name              = "/vpc/${var.name}/flow-logs"
  retention_in_days = 90
}
 
data "aws_iam_policy_document" "flow_assume" {
  statement {
    actions = ["sts:AssumeRole"]
 
    principals {
      type        = "Service"
      identifiers = ["vpc-flow-logs.amazonaws.com"]
    }
  }
}
 
resource "aws_iam_role" "flow" {
  name               = "${var.name}-vpc-flow-logs"
  assume_role_policy = data.aws_iam_policy_document.flow_assume.json
}
 
data "aws_iam_policy_document" "flow" {
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
      "logs:DescribeLogGroups",
      "logs:DescribeLogStreams",
    ]
    resources = ["${aws_cloudwatch_log_group.flow.arn}:*"]
  }
}
 
resource "aws_iam_role_policy" "flow" {
  role   = aws_iam_role.flow.id
  policy = data.aws_iam_policy_document.flow.json
}
 
resource "aws_flow_log" "this" {
  vpc_id                   = aws_vpc.this.id
  traffic_type             = "ALL"
  log_destination_type     = "cloud-watch-logs"
  log_destination          = aws_cloudwatch_log_group.flow.arn
  iam_role_arn             = aws_iam_role.flow.arn
  max_aggregation_interval = 60
 
  tags = { Name = "${var.name}-vpc-flow-log" }
}

CloudWatch Logs is the simplest destination and great for interactive troubleshooting. For long-term retention and large-scale analysis, many teams also (or instead) send flow logs to S3 and query them with Athena, which is considerably cheaper at volume.

Step 8: Outputs#

Other stacks (your EKS cluster, ECS services, databases) need these values:

hcl
# vpc/outputs.tf
output "vpc_id" {
  value = aws_vpc.this.id
}
 
output "public_subnet_ids" {
  value = [for s in aws_subnet.public : s.id]
}
 
output "private_subnet_ids" {
  value = [for s in aws_subnet.private : s.id]
}
 
output "data_subnet_ids" {
  value = [for s in aws_subnet.data : s.id]
}
 
output "nat_public_ips" {
  description = "Static egress IPs. Give these to partners who need to allow-list you."
  value       = aws_eip.nat[*].public_ip
}
 
output "security_group_ids" {
  value = {
    alb = aws_security_group.alb.id
    app = aws_security_group.app.id
    db  = aws_security_group.db.id
  }
}

Step 9: Deploy and Verify#

bash
cd vpc
terraform init
terraform plan -out=tfplan
terraform apply tfplan

NAT gateways take a couple of minutes to become available, and interface endpoints take a little longer. When the apply finishes, check what was built:

bash
VPC_ID=$(terraform output -raw vpc_id)
 
# NAT gateways: expect one per AZ, all "available"
aws ec2 describe-nat-gateways \
  --filter Name=vpc-id,Values=$VPC_ID \
  --query "NatGateways[].[NatGatewayId,SubnetId,State]" --output table
 
# Endpoints: expect "available"
aws ec2 describe-vpc-endpoints \
  --filters Name=vpc-id,Values=$VPC_ID \
  --query "VpcEndpoints[].[ServiceName,VpcEndpointType,State]" --output table
 
# Routes: private tables should show 0.0.0.0/0 via a NAT gateway,
# the data table should only show local and the endpoint prefix lists
aws ec2 describe-route-tables \
  --filters Name=vpc-id,Values=$VPC_ID \
  --query "RouteTables[].[Tags[?Key=='Name']|[0].Value,Routes[].DestinationCidrBlock]" --output json

For deeper verification, the VPC Reachability Analyzer is excellent. Point it at a source and destination (for example an application ENI and a database ENI) and it tells you whether a path exists, and exactly which route table, security group, or NACL blocks it, without sending a single packet.

Deep Dive 1: NAT Gateways vs VPC Endpoints#

These two are often presented as alternatives, but they solve different problems and you will almost always use both. The real question is which traffic should take which path.

What each one does#

  • NAT gateway: lets resources in private subnets start connections to any destination on the internet (third-party APIs, package registries, SaaS webhooks), while blocking connections initiated from the outside. Traffic goes out through the internet gateway.
  • Gateway endpoint: a route-table entry that sends S3 or DynamoDB traffic over the AWS private network. It supports only those two services.
  • Interface endpoint (PrivateLink): a private network interface inside your subnet that represents an AWS service, a partner service, or your own service. Traffic never touches the public internet.

How they compare#

What they can reach

  • NAT gateway: anything on the public internet, including AWS public service endpoints
  • Gateway endpoint: S3 and DynamoDB in the same region
  • Interface endpoint: a large catalogue of AWS services, plus partner and custom PrivateLink services

Cost model (illustrative list prices for us-east-1, so check the AWS pricing pages for your region and the current numbers)

  • NAT gateway: about $0.045 per hour (roughly $33 per month per gateway, even when idle) plus about $0.045 per GB processed
  • Gateway endpoint: free
  • Interface endpoint: about $0.01 per hour per AZ (roughly $7.30 per month per AZ) plus about $0.01 per GB processed

Security posture

  • NAT gateway: your traffic leaves via the internet gateway. You control it with route tables, security groups, and NACLs, but the destination is the public internet
  • Gateway endpoint: traffic stays on the AWS network, and you can attach an endpoint policy (for example, "only allow access to these specific buckets")
  • Interface endpoint: traffic stays on the AWS network, it is protected by its own security group, and it supports endpoint policies too

Availability and scaling

  • NAT gateway: managed and scales automatically (up to tens of Gbps), but zonal, so deploy one per AZ
  • Gateway endpoint: regional and highly available, with nothing to manage
  • Interface endpoint: one network interface per AZ you select, so place them in every AZ you use

Setup effort

  • NAT gateway: trivial, just a default route
  • Gateway endpoint: trivial, attach it to the route tables
  • Interface endpoint: needs a security group, subnets, and private DNS enabled

A worked cost example#

Imagine a private application that downloads and uploads 5 TB per month to S3.

  • Through a NAT gateway: 5 TB is about 5,120 GB, multiplied by $0.045 per GB, which is roughly $230 per month in NAT data processing charges alone.
  • Through an S3 gateway endpoint: $0.

You get the saving by creating one free resource and attaching it to your route tables. That is why S3 and DynamoDB gateway endpoints are the first thing I add to every VPC.

Interface endpoints are a trade-off, not an automatic win#

Interface endpoints have a fixed monthly cost per AZ. Eight endpoints across three AZs is 24 network interfaces, which is on the order of $175 per month before any data charges. That is more than the three NAT gateways cost to keep running.

So the question becomes: does the traffic volume or the security requirement justify it?

  • Yes, worth it: high-volume traffic such as ECR image pulls and CloudWatch Logs shipping from a busy container fleet (the per-GB NAT charge adds up fast), or environments with no internet egress allowed at all (regulated workloads, air-gapped data tiers), where endpoints are the only route to AWS APIs.
  • Probably not worth it: a quiet dev environment calling Secrets Manager a few times an hour. The NAT gateway you already have handles it for pennies.

How I decide#

  1. S3 or DynamoDB? Always use the gateway endpoint. It is free.
  2. High-volume AWS service traffic, or a strict no-internet requirement? Use interface endpoints for those specific services.
  3. Third-party or internet destinations? NAT gateway. Endpoints cannot do this.
  4. Low-volume AWS API calls with no compliance pressure? Let them ride the NAT gateway.

In production you will typically end up with both: endpoints for the heavy and sensitive AWS traffic, and NAT gateways for everything that genuinely has to reach the internet. As a bonus, shifting AWS traffic onto endpoints reduces your NAT bill and your exposure at the same time.

Deep Dive 2: Security Groups vs Network ACLs#

Both filter traffic, so it is tempting to treat them as redundant. They are not. They operate at different layers and behave differently, which is exactly why they complement each other.

The differences#

Where they apply

  • Security group: attached to a network interface (an EC2 instance, ALB, RDS database, Lambda in a VPC, and so on). It is a per-resource firewall
  • NACL: attached to a subnet and applies to everything crossing the subnet boundary

State

  • Security group: stateful. If an inbound request is allowed, the reply is automatically allowed, and vice versa
  • NACL: stateless. Inbound and outbound are evaluated independently, so you must explicitly allow return traffic (the ephemeral port range)

Rule types

  • Security group: allow rules only. Anything not allowed is denied
  • NACL: allow and deny rules, which makes it the only tool here that can explicitly block something

Evaluation

  • Security group: all rules are evaluated together, and any match allows the traffic
  • NACL: rules are evaluated in numeric order, lowest first, and the first match wins. Number rules with gaps (100, 110, 120) so you can insert new ones later

What a rule can point at

  • Security group: CIDR ranges, prefix lists, and other security groups
  • NACL: CIDR ranges only

Defaults

  • Security group: a new group denies all inbound and allows all outbound
  • NACL: the VPC's default NACL allows everything, but a new custom NACL denies everything until you add rules

Tracing one request through both layers#

Follow an HTTPS request from a user to your database-backed app:

  1. User to ALB. The public NACL allows inbound 443 from anywhere. The ALB's security group allows 443 from anywhere.
  2. ALB to application. The public NACL allows the outbound VPC traffic. The private NACL allows inbound on the app port. The app's security group allows that port from the ALB's security group.
  3. Application to database. The private NACL allows outbound to the data subnets on the database port. The data NACL allows inbound on the database port from the private subnets. The database's security group allows it from the app's security group.
  4. Replies. For the security groups, return traffic is automatic. For the NACLs, it only works because we added explicit ephemeral port rules in each direction.

If any layer says no, the packet is dropped. That is defence in depth, and it is also why a missing ephemeral port rule is the number one cause of "my NACL looks right but nothing works".

So which one should you use?#

  • Security groups are your primary control. They are precise, resource-aware, and self-maintaining because group references follow your resources as they scale. Most access decisions belong here.
  • NACLs are a coarse safety net. Use them for tier boundaries (the data subnets accept only the database port from the app subnets), for explicit denies (blocking a known-abusive CIDR range, which security groups cannot do), and where compliance frameworks expect network-layer segmentation.
  • Do not over-engineer NACLs. Because they are stateless and CIDR-only, complex rule sets become hard to maintain and are easy to get subtly wrong. Keep them short, tier-based, and well documented, as we did above.

A good mental model: security groups say who may talk to this resource. NACLs say what may cross this subnet boundary. One is a precise door lock on every room, the other is the fence around the property.

Gotchas That Will Save You an Afternoon#

You cannot easily change the VPC CIDR. You can add secondary CIDR blocks, but the primary one is fixed. Plan it before you build, and coordinate with any other network you may connect to.

The NAT gateway lives in a public subnet. If you place it in a private subnet, or the public route table lacks the internet gateway route, private resources will have no outbound access even though everything looks configured.

Private DNS on interface endpoints needs DNS hostnames. Both enable_dns_support and enable_dns_hostnames must be on, or the service hostname will keep resolving to the public address and bypass your endpoint.

Gateway endpoints only work if they are associated with the right route tables. If a subnet's route table is missing from route_table_ids, its S3 traffic quietly falls back to the NAT gateway and you pay for it.

NACLs see gateway endpoint traffic as traffic to public IPs. That is why the private NACL needs outbound 443 to 0.0.0.0/0 and inbound ephemeral ports from anywhere, even when everything is going through endpoints.

ECR pulls need the S3 gateway endpoint too. Image layers come from S3, so ecr.api and ecr.dkr alone are not enough.

Remember the endpoint security group. An interface endpoint with a security group that does not allow 443 from your clients looks healthy but times out.

Interface endpoints are billed per AZ, around the clock. Review the list regularly and remove the ones nothing uses.

NAT gateways cost money even when idle. For temporary or development environments, set single_nat_gateway = true, or destroy the environment when you are finished.

Production Hardening: What to Add Next#

This VPC is a solid foundation, and here is how it typically grows:

  • VPC endpoint policies to restrict which buckets, tables, or accounts the endpoints can reach, which is a strong defence against data exfiltration
  • AWS Network Firewall or a centralized egress VPC when you need domain-based filtering and deep inspection of outbound traffic
  • IPv6 and an egress-only internet gateway if your workloads or users need it
  • Transit Gateway or VPC peering to connect multiple VPCs and accounts, which is another reason a clean, non-overlapping CIDR plan matters
  • Route 53 Resolver endpoints for hybrid DNS with on-premises networks
  • Flow logs to S3 with Athena for cheap long-term analysis, and alarms on suspicious rejected traffic
  • AWS IPAM for organization-wide CIDR allocation
  • Remote Terraform state in a versioned S3 bucket with locking, plus a module wrapper so every environment gets an identical network
  • Prefix-list-based egress rules in the app security group in place of 0.0.0.0/0 where destinations are well known

Cleaning Up#

bash
terraform destroy

NAT gateways and interface endpoints are the expensive items, so do not forget this step in experimental accounts. Destroying a NAT gateway can take a minute or two, and the Elastic IPs are released afterwards.

Wrapping Up#

A production VPC is not about clever tricks. It is about a handful of sound decisions made early: a roomy and non-overlapping address plan, three AZs, strict tiers, one NAT gateway per AZ, endpoints where they pay for themselves, security groups as the precise control, NACLs as the coarse guardrail, and flow logs so you can see what is happening.

Written as Terraform, all of it becomes reviewable, repeatable, and boring, and boring is exactly what you want from your network. Once this foundation is in place, everything you build on top of it, whether that is ECS, EKS, RDS, or a plain old fleet of EC2 instances, inherits sensible, secure defaults.

If you build this and hit something I did not cover, or have a different take on the NAT versus endpoint trade-off, I would love to hear about it.

Portrait of Navinda Chandrasiri

Written by Navinda Chandrasiri

Senior Software Engineer in Colombo, Sri Lanka, building cloud-native web applications and AI systems.

See my portfolio

ShareLinkedInX

  1. From git push to Global CDN: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline

    Learn to host a Next.js static export on a private S3 bucket with CloudFront, a custom domain, HTTPS, security headers, and automated GitHub to CodePipeline deployments using Terraform.

    AWSTerraformCloudFrontS3

    12 min read
  2. Zero Servers, One Bucket: Deploying a Next.js Static Site to Amazon S3 with Terraform and CodePipeline

    Host a Next.js static export on Amazon S3 website hosting and automate every deployment from GitHub using AWS CodePipeline, CodeBuild, and Terraform, with the trade-offs explained honestly.

    AWSTerraformS3CodePipeline

    12 min read
  3. Zero to Zipwyn: Building a Production Ready Serverless API on AWS with Terraform

    Build a serverless REST API with AWS API Gateway, Lambda, DynamoDB, CloudWatch, and IAM using Terraform. Explore Zipwyn’s architecture, security, monitoring, and local development.

    AWSServerlessTerraformAPI Gateway

    13 min read