콘텐츠로 이동

Lab 06 - Implement Network Traffic Management (Terraform)

목표

공식 Lab 06 - Implement Network Traffic Management에서 다루는 Azure Load Balancer(L4)와 Application Gateway(L7 path-based routing)를 Terraform으로 배포하고, 브라우저와 curl로 검증합니다.

핵심 체험:

  1. Load Balancer — 동일 백엔드 풀의 VM들로 트래픽이 라운드 로빈으로 분산되는 것을 확인
  2. Application Gateway — URL 경로(/image/*, /video/*)에 따라 서로 다른 백엔드로 라우팅되는 것을 확인
  3. L4 vs L7 — 동일 인프라 위에서 두 부하 분산 방식의 차이를 직접 비교

Architecture Diagram

uml diagram


Resources Created

# 리소스 이름/값
1 VNet vnet-{prefix} (10.60.0.0/16)
2 Subnet (backend) snet-backend (10.60.0.0/24)
3 Subnet (appgw) snet-appgw (10.60.1.0/24)
4 NSG nsg-backend-{prefix}
5 NSG Rule AllowHTTP (priority 100)
6 NSG Rule AllowSSH (priority 110)
7 NSG-Subnet 연결 snet-backend ↔ NSG
8–9 Public IP (VM) pip-vm0-{prefix}, pip-vm1-{prefix}
10–11 NIC nic-vm0-{prefix}, nic-vm1-{prefix}
12–13 Linux VM vm0-{prefix}, vm1-{prefix} (Ubuntu 24.04)
14 Public IP (LB) pip-lb-{prefix}
15 Load Balancer lb-{prefix} (Standard)
16 LB Backend Pool be-pool
17–18 NIC-LB Pool 연결 vm0, vm1 → be-pool
19 LB Health Probe hp-http (TCP 80)
20 LB Rule rule-http (port 80)
21 Public IP (AppGw) pip-appgw-{prefix}
22 Application Gateway appgw-{prefix} (Standard_v2)
23–24 NIC-AppGw Pool 연결 (default) vm0, vm1 → be-default
25 NIC-AppGw Pool 연결 (image) vm0 → be-image
26 NIC-AppGw Pool 연결 (video) vm1 → be-video
27 random_password VM admin password (24자)

비용 주의

Application Gateway (Standard_v2, capacity 2)와 VM ×2 는 시간당 과금됩니다. 실습 후 반드시 terraform destroy 하세요.


Prerequisite

항목 설명
권한 할당된 Resource Group에 Contributor 이상
도구 Azure CLI, Terraform 1.6+
인증 az login 후 올바른 subscription 선택
선행 Lab Lab 04 - Virtual Networking 완료 권장

Concept Mapping (Official Lab 06)

공식 Lab 06 주제 이 모듈에서의 위치
ARM template으로 인프라 배포 Terraform network.tf + vm.tf (VNet, Subnet, VM, NSG)
Azure Load Balancer 구성 lb.tf — Standard Public LB, Backend Pool, Health Probe, Rule
Application Gateway 구성 appgw.tf — Standard_v2, URL path map, path-based routing
LB Health Probe lb.tf — azurerm_lb_probe (TCP 80)
AppGw Path-based routing appgw.tf — url_path_map (/image/, /video/)
트래픽 분산 검증 브라우저/curl 로 LB IP 반복 접속 → 서로 다른 VM 응답 확인

Load Balancer vs Application Gateway

배포 위치 차이

항목 Public LB Internal LB Application Gateway
VNet 배포 ✗ (리전 리소스) ✓ (서브넷에 배포) ✓ (전용 서브넷 필수)
Frontend IP Public IP Private IP (서브넷에서 할당) Public IP 또는 Private IP
Backend 참조 NIC 기반 (VNet 내 VM) NIC 기반 (동일 VNet) Backend Pool (IP/FQDN)

LB Multi-Frontend: Public + Private 동시 사용

하나의 Standard Load Balancer에 여러 Frontend IP configuration을 추가할 수 있습니다.
즉, Public frontend(외부 트래픽)과 Private frontend(내부 트래픽)을 한 LB에서 동시에 서비스 가능합니다.

# Public frontend
frontend_ip_configuration {
  name                 = "fe-public"
  public_ip_address_id = azurerm_public_ip.lb.id
}
# Internal frontend (같은 LB)
frontend_ip_configuration {
  name      = "fe-internal"
  subnet_id = azurerm_subnet.backend.id
  private_ip_address_allocation = "Dynamic"
}

기능 비교

항목 Load Balancer Application Gateway
OSI Layer Layer 4 (TCP/UDP) Layer 7 (HTTP/HTTPS)
라우팅 기준 IP + Port URL path, Host header, Cookie
프로토콜 TCP, UDP HTTP, HTTPS, WebSocket
SSL Termination ✗ ✓
WAF ✗ ✓ (WAF_v2 tier)
세션 유지 소스 IP hash Cookie-based affinity
가격 상대적 저렴 상대적 비쌈 (capacity 기반)
주 용도 DB, non-HTTP 서비스, 순수 분산 Web App, API, 마이크로서비스

Application Gateway 전용 서브넷 요구사항

출처: Application Gateway infrastructure configuration

Application Gateway는 VNet 내 전용 서브넷(dedicated subnet)에만 배포됩니다. 이 서브넷에는 VM, NIC 등 다른 리소스를 함께 배포할 수 없습니다.

항목 규칙
다른 리소스 공유 ✗ 불가 — Application Gateway 인스턴스만 허용
서브넷 이름 GatewaySubnet 사용 불가 (VPN Gateway 예약 이름)
v1 SKU 권장 크기 /26 이상 (최대 32 인스턴스)
v2 SKU 권장 크기 /24 이상 (최대 125 인스턴스, 자동 스케일링 여유 확보)
IP 소비 방식 인스턴스당 1개 + Private frontend IP 1개 + Azure 예약 5개

NSG 규칙 필수

Application Gateway v2 서브넷에 NSG를 붙이면 반드시 다음 인바운드 규칙을 허용해야 합니다.
Azure 관리 플레인 통신에 필요합니다.

방향 포트 소스 설명
Inbound TCP 65200–65535 GatewayManager v2 관리 플레인
Inbound Any AzureLoadBalancer Health probe

이 Lab에서는 snet-appgw(10.60.1.0/24 = /24)를 전용 서브넷으로 사용합니다.


Step-by-Step

Terraform 코드 위치: labs/terraform/lab06-network-traffic/

1) Prepare variables

cd labs/terraform/lab06-network-traffic
cp terraform.tfvars.example terraform.tfvars

에디터로 terraform.tfvars를 열고 다음을 설정합니다.

  • resource_group_name (필수) — 강사가 알려준 본인 RG 이름

2) Login to Azure

az login
az account show -o table

3) Initialize Terraform

terraform init

4) Plan

terraform plan

terraform plan에서 볼 것

  • 추가될 리소스 수 — 총 27개
  • Application Gateway — sku = Standard_v2, capacity = 2, path-based routing 규칙
  • Load Balancer — sku = Standard, frontend IP + backend pool + health probe + rule
  • VM custom_data — nginx 설치 + 커스텀 index.html 생성 스크립트 (base64)

5) Apply

terraform apply

프롬프트에 yes를 입력합니다.

배포 시간

Application Gateway는 프로비저닝에 5~10분 소요됩니다. 전체 배포는 약 10~15분 걸릴 수 있습니다.

예상 출력 (요약)
Apply complete! Resources: 27 added, 0 changed, 0 destroyed.

Outputs:
appgw_image_url    = "http://x.x.x.x/image/"
appgw_public_ip    = "x.x.x.x"
appgw_url          = "http://x.x.x.x/"
appgw_video_url    = "http://x.x.x.x/video/"
lb_public_ip       = "y.y.y.y"
lb_url             = "http://y.y.y.y/"
location           = "koreacentral"
resource_group_name = "rg-az104-student01"
vm_admin_password  = <sensitive>
vm_admin_username  = "azureuser"
vm_public_ips      = ["a.a.a.a", "b.b.b.b"]
vnet_name          = "vnet-az104-lab06"

6) Check outputs

terraform output
terraform output lb_public_ip
terraform output appgw_public_ip

Load Balancer 테스트

LB 라운드 로빈은 브라우저로 확인할 수 없습니다

Azure Load Balancer는 L4 (TCP 연결) 단위로 분산합니다. 브라우저는 같은 서버와 TCP 연결을 유지(HTTP Keep-Alive)하므로, 새로고침을 해도 연결이 끊기지 않는 한 계속 같은 VM으로 요청이 갑니다. 이것은 LB의 잘못이 아닌 L4 분산의 정상 동작입니다.

라운드 로빈을 확인하려면 매 요청마다 새 TCP 연결을 맺는 curl --no-keepalive를 사용해야 합니다.

curl로 확인 (라운드 로빈)

LB_IP=$(terraform output -raw lb_public_ip)

for i in {1..6}; do
  curl -s --no-keepalive "http://${LB_IP}/" | grep "<h1>"
done
for /f "tokens=*" %a in ('terraform output -raw lb_public_ip') do set LB_IP=%a

for /L %i in (1,1,6) do curl -s --no-keepalive "http://%LB_IP%/" | findstr "<h1>"
예상 결과

<h1>Hello from vm-0 (az104-lab06)</h1>
<h1>Hello from vm-1 (az104-lab06)</h1>
<h1>Hello from vm-0 (az104-lab06)</h1>
<h1>Hello from vm-1 (az104-lab06)</h1>
...
--no-keepalive로 매번 새 TCP 연결을 맺으면 LB가 두 VM에 라운드 로빈으로 분산하는 것을 확인할 수 있습니다.

L4 LB의 핵심 동작

Load Balancer는 HTTP 헤더나 URL 경로를 인식하지 못합니다. TCP 연결(5-tuple 해시) 기준으로 분산하며, 한 번 연결이 맺어지면 그 연결의 모든 요청은 같은 VM으로 갑니다.


Application Gateway 테스트

기본 경로 (/)

APPGW_IP=$(terraform output -raw appgw_public_ip)
curl -s "http://${APPGW_IP}/"
for /f "tokens=*" %a in ('terraform output -raw appgw_public_ip') do set APPGW_IP=%a
curl -s "http://%APPGW_IP%/"

be-default 풀(vm-0 + vm-1)에 라운드 로빈으로 분산됩니다.

여러 번 실행해 vm-0 / vm-1이 번갈아 응답하는 것을 확인합니다.

APPGW_IP=$(terraform output -raw appgw_public_ip)

for i in {1..6}; do
  curl -s "http://${APPGW_IP}/" | grep "<h1>"
done
for /f "tokens=*" %a in ('terraform output -raw appgw_public_ip') do set APPGW_IP=%a

for /L %i in (1,1,6) do curl -s "http://%APPGW_IP%/" | findstr "<h1>"

AppGw는 브라우저에서도 라운드 로빈이 됩니다

Application Gateway는 L7 (HTTP 요청) 단위로 분산합니다. 브라우저가 AppGw와 Keep-Alive 연결을 유지해도, AppGw는 각 HTTP 요청마다 독립적으로 백엔드 VM을 선택합니다. 클라이언트 ↔ AppGw 연결과 AppGw ↔ 백엔드 연결이 완전히 분리되기 때문입니다.

LB(--no-keepalive 필요)와 달리 AppGw는 별도 조치 없이도 라운드 로빈이 확인됩니다.

/image/ 경로 → vm-0

curl -s "http://${APPGW_IP}/image/"
curl -s "http://%APPGW_IP%/image/"
예상 결과

<h1>Image Server — vm-0</h1><p>Serving images from vm-0</p>
/image/* 경로는 항상 vm-0으로 라우팅됩니다.

/video/ 경로 → vm-1

curl -s "http://${APPGW_IP}/video/"
curl -s "http://%APPGW_IP%/video/"
예상 결과

<h1>Video Server — vm-1</h1><p>Serving videos from vm-1</p>
/video/* 경로는 항상 vm-1로 라우팅됩니다.

핵심 포인트 — Path-based Routing

Application Gateway는 L7 (HTTP) 수준에서 동작하여 URL 경로를 파싱하고, 경로별로 서로 다른 백엔드 풀에 요청을 전달할 수 있습니다. 이것이 Load Balancer와의 가장 큰 차이입니다.

URL 경로 라우팅 대상
/ (기본) be-default (vm-0 + vm-1)
/image/* be-image (vm-0)
/video/* be-video (vm-1)

Verify - Azure Portal

  1. Resource Group → LB, Application Gateway, VM ×2, VNet 등이 보이는지 확인합니다.
  2. Load Balancer → Backend pools → be-pool 에 vm-0, vm-1 이 있고 Health status가 Healthy인지 확인.
  3. Load Balancer → Load balancing rules → rule-http (port 80, probe: hp-http) 확인.
  4. Application Gateway → Backend health → be-default, be-image, be-video 모두 Healthy 확인.
  5. Application Gateway → Rules → rule-path-based → URL path map에서 /image/*, /video/* 규칙 확인.

추가 확인 (Portal)

  • Application Gateway → Monitoring → Metrics 에서 요청 수, 응답 시간 그래프 확인
  • Load Balancer → Monitoring → Metrics 에서 Data Path Availability, Health Probe Status 확인
  • VM → Networking → effective security rules 에서 NSG 규칙이 올바르게 적용되는지 확인

Cleanup (Teardown)

terraform destroy

프롬프트에 yes를 입력합니다.

비용 방지

Application Gateway와 VM은 시간당 과금됩니다. 실습이 끝나면 반드시 terraform destroy를 실행하세요. Application Gateway 삭제에 수 분 소요될 수 있습니다.

terraform destroy 첫 실행 시 에러가 날 수 있습니다

Azure는 NIC(네트워크 인터페이스)가 연결된 상태에서 LB / AppGw를 삭제하면 에러를 반환하는 경우가 있습니다. Terraform이 병렬로 리소스를 삭제하다가 순서 충돌이 발생하는 경우입니다.

해결 방법: 에러가 발생하면 같은 명령을 한 번 더 실행합니다. 첫 실행에서 VM / NIC가 먼저 삭제되므로, 두 번째 실행에서 LB / AppGw가 정상적으로 삭제됩니다.


Terraform Files

파일 역할
versions.tf Terraform / provider 버전 제약
providers.tf azurerm provider
variables.tf prefix, RG, VM size, VNet/subnet CIDR 등
main.tf RG data source, random_password, locals
network.tf VNet, Subnet ×2 (backend, appgw), NSG, NSG Rules
vm.tf Linux VM ×2, PIP, NIC, nginx custom_data
lb.tf Public Load Balancer, Backend Pool, Probe, Rule
appgw.tf Application Gateway, Backend Pools, URL Path Map, Routing Rule
outputs.tf LB/AppGw IP/URL, VM IPs, credentials
terraform.tfvars.example 변수 예시 파일 (비밀 값 없음)

Troubleshooting

증상 원인 해결
LB IP 접속 시 timeout VM 에 nginx 미설치 (custom_data 실패) VM에 SSH 접속 → systemctl status nginx 확인
AppGw Backend Unhealthy Health probe 실패 VM에서 curl localhost 확인, NSG HTTP 규칙 확인
AppGw 배포 실패 snet-appgw 크기 부족 또는 다른 리소스 존재 subnet 에 다른 리소스가 없는지 확인 (/24 권장)
/image/ 접근 시 502 Backend VM 응답 없음 SSH로 vm-0 접속 → /var/www/html/image/index.html 존재 여부 확인
LB에서 한 VM만 응답 Health probe 실패 (다른 VM) Portal → LB → Backend pool health 확인
배포 시 quota 오류 VM SKU 할당량 초과 vm_size를 Standard_B2s 등으로 변경

Cost & Caution

실수 방지

terraform.tfvars의 resource_group_name이 반드시 본인 RG인지 확인한 뒤 apply하세요. Application Gateway는 배포/삭제에 시간이 걸리므로 잘못된 RG에 배포하면 정리가 번거롭습니다.