🌍 Networking

Subnet

Subnet

A logical subdivision of an IP network. Written in CIDR notation. A VPC component.

📖 Detailed Explanation

A subnet is a technique for dividing one large IP network into smaller logical network segments. For example, if a company has been allocated the 10.0.0.0/16 network, it can split it into 10.0.1.0/24 (development team), 10.0.2.0/24 (operations team), and 10.0.3.0/24 (DB server) to improve network management efficiency and security.

Subnets are expressed in CIDR (Classless Inter-Domain Routing) notation. In 10.0.1.0/24, /24 refers to the subnet mask: the leading 24 bits are the network address, and the remaining 8 bits (2^8 = 256 addresses, 254 actually usable) are the host address. /24 is equivalent to 255.255.255.0, and /16 is allocated 65,536 IPs and /28 is allocated 16 IPs.

In cloud environments, subnets are a core component of a VPC (Virtual Private Cloud). AWS, GCP, and Azure all distinguish between Public Subnets (directly connected to the internet) and Private Subnets (for internal communication only). Web servers are placed in a Public Subnet and databases in a Private Subnet to strengthen security. Outbound internet access from a Private Subnet is handled through a NAT Gateway.

In a high availability (HA) architecture, subnets are distributed across at least 2 Availability Zones (AZs). For example, you create a Public/Private Subnet in each of ap-northeast-2a and ap-northeast-2c, for a total of 4 subnets. This way, the service does not go down even if a failure occurs in one AZ. It is recommended to design CIDR blocks with more headroom than /24, at a size of /20 to /22, in anticipation of future expansion.

💻 Code Example

# AWS VPC와 서브넷 구성 (Terraform)
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = { Name = "production-vpc" }
}

# Public Subnet (AZ-a) - 웹 서버, ALB 배치
resource "aws_subnet" "public_a" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = "10.0.1.0/24"    # 254개 IP
  availability_zone       = "ap-northeast-2a"
  map_public_ip_on_launch = true

  tags = { Name = "public-subnet-a", Type = "public" }
}

# Public Subnet (AZ-c) - HA 구성용
resource "aws_subnet" "public_c" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = "10.0.2.0/24"
  availability_zone       = "ap-northeast-2c"
  map_public_ip_on_launch = true

  tags = { Name = "public-subnet-c", Type = "public" }
}

# Private Subnet (AZ-a) - DB, 애플리케이션 서버
resource "aws_subnet" "private_a" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.10.0/24"
  availability_zone = "ap-northeast-2a"

  tags = { Name = "private-subnet-a", Type = "private" }
}

# Private Subnet (AZ-c) - HA 구성용
resource "aws_subnet" "private_c" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.11.0/24"
  availability_zone = "ap-northeast-2c"

  tags = { Name = "private-subnet-c", Type = "private" }
}

# Internet Gateway - Public Subnet용
resource "aws_internet_gateway" "main" {
  vpc_id = aws_vpc.main.id
  tags   = { Name = "main-igw" }
}

# NAT Gateway - Private Subnet 아웃바운드용
resource "aws_eip" "nat" {
  domain = "vpc"
}

resource "aws_nat_gateway" "main" {
  allocation_id = aws_eip.nat.id
  subnet_id     = aws_subnet.public_a.id  # Public Subnet에 배치

  tags = { Name = "main-nat-gateway" }
}
import boto3
import ipaddress

# CIDR 계산 유틸리티
def calculate_cidr(cidr_block):
    """CIDR 블록 정보 계산"""
    network = ipaddress.ip_network(cidr_block, strict=False)

    print(f"네트워크 주소: {network.network_address}")
    print(f"브로드캐스트: {network.broadcast_address}")
    print(f"서브넷 마스크: {network.netmask}")
    print(f"총 IP 수: {network.num_addresses}")
    print(f"사용 가능 IP: {network.num_addresses - 5}")  # AWS는 5개 예약
    print(f"IP 범위: {list(network.hosts())[0]} ~ {list(network.hosts())[-1]}")

    return network

# 예제: /24 블록 분석
calculate_cidr("10.0.1.0/24")
# 네트워크 주소: 10.0.1.0
# 총 IP 수: 256
# 사용 가능 IP: 251 (AWS는 5개 예약: .0, .1, .2, .3, .255)

# boto3로 VPC 서브넷 생성
ec2 = boto3.client('ec2', region_name='ap-northeast-2')

# VPC 생성
vpc_response = ec2.create_vpc(
    CidrBlock='10.0.0.0/16',
    TagSpecifications=[{
        'ResourceType': 'vpc',
        'Tags': [{'Key': 'Name', 'Value': 'production-vpc'}]
    }]
)
vpc_id = vpc_response['Vpc']['VpcId']

# Public Subnet 생성
public_subnet = ec2.create_subnet(
    VpcId=vpc_id,
    CidrBlock='10.0.1.0/24',
    AvailabilityZone='ap-northeast-2a',
    TagSpecifications=[{
        'ResourceType': 'subnet',
        'Tags': [
            {'Key': 'Name', 'Value': 'public-subnet-a'},
            {'Key': 'Type', 'Value': 'public'}
        ]
    }]
)

# Private Subnet 생성
private_subnet = ec2.create_subnet(
    VpcId=vpc_id,
    CidrBlock='10.0.10.0/24',
    AvailabilityZone='ap-northeast-2a',
    TagSpecifications=[{
        'ResourceType': 'subnet',
        'Tags': [
            {'Key': 'Name', 'Value': 'private-subnet-a'},
            {'Key': 'Type', 'Value': 'private'}
        ]
    }]
)

print(f"Public Subnet ID: {public_subnet['Subnet']['SubnetId']}")
print(f"Private Subnet ID: {private_subnet['Subnet']['SubnetId']}")
# AWS CLI로 VPC 서브넷 관리

# VPC 생성
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=production-vpc}]'

# VPC ID 확인
VPC_ID=$(aws ec2 describe-vpcs \
    --filters "Name=tag:Name,Values=production-vpc" \
    --query 'Vpcs[0].VpcId' --output text)

# Public Subnet 생성 (AZ-a)
aws ec2 create-subnet \
    --vpc-id $VPC_ID \
    --cidr-block 10.0.1.0/24 \
    --availability-zone ap-northeast-2a \
    --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=public-subnet-a},{Key=Type,Value=public}]'

# Private Subnet 생성 (AZ-a)
aws ec2 create-subnet \
    --vpc-id $VPC_ID \
    --cidr-block 10.0.10.0/24 \
    --availability-zone ap-northeast-2a \
    --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=private-subnet-a},{Key=Type,Value=private}]'

# 서브넷 목록 조회
aws ec2 describe-subnets \
    --filters "Name=vpc-id,Values=$VPC_ID" \
    --query 'Subnets[*].{ID:SubnetId,CIDR:CidrBlock,AZ:AvailabilityZone,Public:MapPublicIpOnLaunch}' \
    --output table

# Internet Gateway 생성 및 연결
IGW_ID=$(aws ec2 create-internet-gateway \
    --query 'InternetGateway.InternetGatewayId' --output text)
aws ec2 attach-internet-gateway --vpc-id $VPC_ID --internet-gateway-id $IGW_ID

# CIDR 계산 (Linux ipcalc)
ipcalc 10.0.1.0/24
# Network:   10.0.1.0/24
# Netmask:   255.255.255.0
# HostMin:   10.0.1.1
# HostMax:   10.0.1.254
# Hosts/Net: 254

# 서브넷 내 사용 가능 IP 수 확인
aws ec2 describe-subnets \
    --subnet-ids subnet-xxxxx \
    --query 'Subnets[0].AvailableIpAddressCount'

🗣️ Say It Like This in Practice

💬 In a VPC design meeting
"Let's set the production VPC to 10.0.0.0/16 and place the Public Subnets as /24 across 2 AZs. We need at least 2 Private Subnets because of RDS Multi-AZ, and we have to create a separate /20 subnet for the EKS nodes so we don't run out of Pod IPs. A total of 6 subnets looks appropriate."
💬 In a security review meeting
"The DB server must not be in a Public Subnet. We need to move it to a Private Subnet and configure the Security Group so that port 3306 is accessible only from the web server. If external API calls are needed, I'll modify the routing table so they go out through a NAT Gateway."
💬 In a troubleshooting situation
"You're saying the EC2 instance can't connect to the internet? First, please check whether the subnet is Public or Private. If it is a Private Subnet, you need to check whether there is a NAT Gateway and whether the route table has a 0.0.0.0/0 → NAT route. If it is Public, check the IGW attachment and whether a public IP has been assigned."

⚠️ Common Mistakes & Cautions

❌
Setting the CIDR block too small

If you create it as /28 (11 IPs), you will run out of IPs when the service expands. Since a subnet CIDR cannot be changed later, allow some headroom from the start with /24 or larger. When using EKS, /20 is recommended.

❌
Placing subnets in only a single AZ

If you create subnets only in ap-northeast-2a, the entire service goes down when that AZ fails. RDS Multi-AZ and ALB require subnets in at least 2 AZs. Always configure an even number of them.

❌
Placing all resources in Public without distinguishing Public/Private

If you put databases and backend servers in a Public Subnet, they are exposed to external attacks. Place only the ALB and Bastion, which need a direct internet connection, in Public, and be sure to place everything else in a Private Subnet.

✅
Correct subnet design pattern

A configuration of VPC /16 → Public /24 x 2 AZ + Private /24 x 2 AZ is the standard. Plan CIDR blocks so they do not overlap (in preparation for VPC Peering), and tag them clearly by purpose. Capacity planning must account for the 5 IPs AWS reserves per subnet.

🔗 Related Terms

📚 Learn More