콘텐츠로 이동

Lab 92 - AKS Monitoring (Terraform + OTel)

목표

AKS에 배포된 마이크로서비스의 Traces, Metrics, Logs를 OpenTelemetry Collector를 통해 Azure Monitor (Application Insights)로 전송하고, Portal에서 분산 추적과 메트릭을 확인합니다.

핵심 체험:

  1. Azure Monitor 백엔드 생성 — Log Analytics Workspace + Application Insights (Terraform)
  2. OTel Collector 배포 — Kubernetes에 Collector 배포, Azure Monitor exporter 연동
  3. 분산 추적 (Distributed Tracing) — Application Insights Transaction Search에서 end-to-end trace 확인
  4. 메트릭 & 로그 — Live Metrics, Log Analytics 쿼리 (KQL)
  5. Alert 생성 — 에러율 기반 Alert Rule 설정

Architecture Diagram

uml diagram


Resources Created (Terraform)

리소스 이름 설명
Log Analytics Workspace law-{prefix} 로그, 메트릭 저장소 (KQL 쿼리 대상)
Application Insights appi-{prefix} 분산 추적, Live Metrics, 성능 모니터링

비용

Log Analytics는 수집 데이터량 기반 과금 (PerGB2018). 실습 규모에서는 거의 무료에 가깝습니다 (Free tier: 5GB/월).

Container Insights 활성화 시 자동 배포되는 리소스

az aks enable-addons --addons monitoring 실행 시 AKS가 kube-system 네임스페이스에 다음 에이전트를 자동 배포합니다.

리소스 종류 역할
ama-logs DaemonSet 노드당 1 Pod — 각 노드의 /var/log/containers에서 컨테이너 stdout/stderr 수집 → ContainerLogV2, Perf
ama-logs-rs Deployment (ReplicaSet) 클러스터당 1 Pod — K8s API 폴링으로 Pod/Node 인벤토리, 메트릭 수집 → KubePodInventory, KubeNodeInventory, InsightsMetrics
# 배포 확인
kubectl get ds ama-logs -n kube-system
kubectl get deployment ama-logs-rs -n kube-system

AMA (Azure Monitor Agent)

ama-logs는 Microsoft가 관리하는 Azure Monitor Agent (AMA) 기반 에이전트입니다. AKS 클러스터에 직접 설치하지 않아도 되며, Container Insights add-on 활성화만으로 자동 배포·업데이트됩니다.
→ 참고: Enable monitoring for AKS clusters


Prerequisite

항목 설명
AKS + App Lab 90 + Lab 91 완료
kubectl AKS 자격 증명 설정 완료
Terraform 1.6+ (Part 1 — 로컬 터미널에서 실행)
인증 az login 완료
매니페스트 gitops-manifests 저장소 clone 완료 (Lab 91 참조)

Azure Cloud Shell 사용 범위

단계 Cloud Shell 비고
Part 1 (Terraform — LAW + APPI 생성) ❌ 로컬만 Terraform state 필요
Part 1 Step 0 (Container Insights 활성화) ✅ 사용 가능 az CLI만 사용
Part 2 (OTel Collector 배포) ✅ 사용 가능 kubectl + az CLI
Part 3 (텔레메트리 확인) ✅ 사용 가능 kubectl + curl
Part 4 (KQL 쿼리) — Azure Portal에서 실행

OTel Collector 설정 설명

otel-collector.yaml 하나에 Namespace, ConfigMap, Deployment, Service 4개의 Kubernetes 리소스가 정의되어 있습니다.

매니페스트 구조

리소스 이름 역할
Namespace otel-collector Collector 전용 네임스페이스 격리
ConfigMap otel-collector-config Collector 파이프라인 설정 (config.yaml)
Deployment otel-apps Collector Pod (contrib 이미지, 1 replica)
Service otel-apps 앱이 접근하는 엔드포인트 (otel-apps.otel-collector:4317/4318)

파이프라인 설정 (ConfigMap)

App (OTLP) → [Receiver] → [Processor] → [Exporter] → Azure Monitor
구성 요소 설정 역할
Receiver otlp — gRPC(:4317), HTTP(:4318) 앱의 OTel Agent가 보내는 traces/metrics/logs 수신
Processor memory_limiter (512MiB 상한) 메모리 초과 방지 — 초과 시 데이터 드롭
Processor batch (1024건 / 5초) 개별 전송 대신 묶어서 보내 네트워크 효율 향상
Exporter azuremonitor Application Insights Connection String으로 전송
Exporter debug (verbosity: basic) Pod stdout에 수신 건수 출력 (디버깅용)

인증 방식

Deployment의 환경변수 APPLICATIONINSIGHTS_CONNECTION_STRING을 Secret (azure-monitor-secret)에서 주입받아, ConfigMap의 ${APPLICATIONINSIGHTS_CONNECTION_STRING} placeholder를 런타임에 치환합니다.

운영 환경 권장 사항

  • debug exporter 제거
  • memory_limiter 값을 노드 리소스에 맞게 조정
  • Collector를 DaemonSet 또는 Deployment(replica 2+)로 운영
  • Sampling 설정 추가 (예: probabilistic_sampler, rate 0.1)

Step-by-Step

Part 1: Azure Monitor 백엔드 생성 (Terraform)

Terraform 환경에서 실행

Part 1은 Terraform이 구성된 환경 (로컬 터미널 또는 lab 환경)에서 실행합니다.
Cloud Shell에는 Terraform state가 없으므로 terraform 명령이 동작하지 않습니다.

1) Prepare variables

cd labs/terraform/lab92-aks-monitoring
cp terraform.tfvars.example terraform.tfvars

terraform.tfvars에서 resource_group_name을 본인 RG로 설정합니다.

2) Deploy (Log Analytics + Application Insights 생성)

terraform init
terraform plan
terraform apply
예상 출력
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:
application_insights_connection_string = <sensitive>
application_insights_name              = "appi-az104-lab92"
log_analytics_workspace_name           = "law-az104-lab92"
...

3) Container Insights 활성화 (AKS)

순서 주의

이 단계는 Step 2 완료 후 실행해야 합니다. Log Analytics Workspace가 먼저 존재해야 Container Insights가 연결할 수 있습니다.

AKS 클러스터에 Container Insights를 활성화하면 노드/Pod CPU, Memory, 컨테이너 로그(ContainerLogV2)를 Log Analytics로 자동 수집합니다.

AKS_NAME=$(cd ../lab90-aks && terraform output -raw aks_cluster_name)
RG=$(cd ../lab90-aks && terraform output -raw resource_group_name)

az aks enable-addons --addons monitoring \
  -g "$RG" -n "$AKS_NAME" \
  --workspace-resource-id "$(terraform output -raw log_analytics_workspace_id)" \
  --no-wait
RG="<본인 RG 이름>"
AKS_NAME="<AKS 클러스터 이름>"  # 예: aks-az104-aks

# LAW 리소스 ID 조회 (Step 2에서 생성됨)
LAW_ID=$(az monitor log-analytics workspace show \
  -g "$RG" -n "law-az104-lab92" \
  --query id -o tsv)

az aks enable-addons --addons monitoring \
  -g "$RG" -n "$AKS_NAME" \
  --workspace-resource-id "$LAW_ID" \
  --no-wait

Container Insights vs OTel Collector

구분 Container Insights OTel Collector
수집 대상 노드/Pod 인프라 메트릭 (CPU, Memory, Network, Disk), 컨테이너 stdout/stderr 로그 애플리케이션 수준 Traces, Metrics, Logs (OTel SDK/Agent 발생)
저장 테이블 ContainerLogV2, Perf, InsightsMetrics, KubePodInventory 등 requests, dependencies, traces, customMetrics
설정 AKS add-on 활성화 (코드 변경 없음) Collector Pod 배포 + Secret

둘 다 활성화하면 인프라 + 앱 양쪽을 한 곳(Log Analytics)에서 확인할 수 있습니다.

4) Connection String 확인

terraform output -raw application_insights_connection_string

Application Insights (appi-az104-lab92) → Overview → Connection String 복사

az monitor app-insights component show \
  -g "<본인 RG 이름>" -a "appi-az104-lab92" \
  --query connectionString -o tsv

이 값을 다음 단계에서 OTel Collector Secret에 주입합니다.


Part 2: OTel Collector 배포 (Kubernetes)

Cloud Shell에서 실행

Part 2 이후는 Cloud Shell (또는 kubectl이 연결된 터미널)에서 실행합니다.
Cloud Shell에는 Terraform이 없으므로, Connection String은 Portal 또는 az CLI로 확인하세요.

0) gitops-manifests 저장소 확인

Lab 91에서 이미 clone한 저장소로 이동합니다.

cd gitops-manifests
# Cloud Shell 홈 디렉토리의 저장소로 이동
cd ~/gitops-manifests

clone하지 않았다면

git clone https://github.com/noisonnoiton-shop/gitops-manifests.git
cd gitops-manifests

1) Secret 생성

# Cloud Shell — Connection String을 az CLI로 조회
RG="<본인 RG 이름>"  # 예: rg-krc-dev-lab90-01

CONN_STR=$(az monitor app-insights component show \
  -g "$RG" -a "appi-az104-lab92" \
  --query connectionString -o tsv)

kubectl create namespace otel-collector --dry-run=client -o yaml | kubectl apply -f -

kubectl create secret generic azure-monitor-secret \
  -n otel-collector \
  --from-literal=connection-string="${CONN_STR}" \
  --dry-run=client -o yaml | kubectl apply -f -
CONN_STR=$(terraform output -raw application_insights_connection_string)

kubectl create namespace otel-collector --dry-run=client -o yaml | kubectl apply -f -

kubectl create secret generic azure-monitor-secret \
  -n otel-collector \
  --from-literal=connection-string="${CONN_STR}" \
  --dry-run=client -o yaml | kubectl apply -f -

2) OTel Collector 배포

kubectl apply -f clusters/az104-aks/otel-collector/otel-collector.yaml

3) Collector 상태 확인

kubectl get all -n otel-collector
kubectl logs -n otel-collector deployment/otel-apps --tail=20
예상 출력
2026-04-30T... info  service@v0.151.0/service.go:... msg="Everything is ready."
2026-04-30T... info  exporters/azuremonitor ... msg="Azure Monitor exporter initialized"

Collector 정상 확인

로그에 Everything is ready 메시지가 보이면 정상입니다. azuremonitor exporter가 초기화되었는지 확인하세요.


Part 3: 텔레메트리 확인 (Portal)

앱 서비스들이 이미 otel-apps.otel-collector:4318로 데이터를 보내고 있으므로, Collector가 배포되면 즉시 데이터가 Azure Monitor로 흐릅니다.

참고: Application Insights Experiences

1) 트래픽 생성

INGRESS_IP=$(kubectl get svc -n app-routing-system nginx \
  -o jsonpath='{.status.loadBalancer.ingress[0].ip}')

echo "Ingress IP: ${INGRESS_IP}"

for i in {1..20}; do
  curl -s "http://awesome-apigateway.${INGRESS_IP}.nip.io/api/products" > /dev/null
  curl -s "http://awesome-apigateway.${INGRESS_IP}.nip.io/api/accounts" > /dev/null
done

echo "요청 20회 완료 — 2~3분 후 Application Insights에서 확인 가능"
for /f "tokens=*" %a in ('kubectl get svc -n app-routing-system nginx -o jsonpath^="{.status.loadBalancer.ingress[0].ip}"') do set INGRESS_IP=%a

for /L %i in (1,1,20) do (
  curl -s "http://awesome-apigateway.%INGRESS_IP%.nip.io/api/products" > NUL
  curl -s "http://awesome-apigateway.%INGRESS_IP%.nip.io/api/accounts" > NUL
)

echo 요청 20회 완료

2) Application Map — 서비스 의존 관계

  1. Application Insights → Investigate → Application map
  2. 서비스 간 의존 관계 그래프가 자동 생성됩니다 (apigateway → product, account, cart 등).
  3. 각 노드(서비스)를 클릭하면:
    • Investigate failures — 해당 서비스의 실패 분석
    • Investigate performance — 응답 시간 분석
    • Go to details — End-to-end transaction details (Gantt chart)

Application Map

Application Map은 분산 앱의 토폴로지를 시각화합니다. 각 노드에 평균 응답 시간, 실패율이 표시되어 병목이나 장애 서비스를 한눈에 파악할 수 있습니다.
→ Application map: Triage distributed applications

3) Performance — 응답 시간 분석

  1. Application Insights → Investigate → Performance
  2. Operations 탭에서 전체 요청 목록, 평균 응답 시간, 호출 횟수를 확인합니다.
  3. 느린 요청을 클릭 → Drill into → 샘플 선택 → End-to-end transaction details 에서 호출 체인(Gantt chart) 확인

Dependency 확인

Performance 화면 하단의 Dependencies 탭에서 외부 호출(MySQL, Redis, RabbitMQ 등) 응답 시간도 확인할 수 있습니다.

4) Failures — 실패 분석

  1. Application Insights → Investigate → Failures
  2. Operations 탭 — 실패한 요청의 HTTP 상태 코드별 분류
  3. Exceptions 탭 — 서비스에서 발생한 예외(Exception) 목록
  4. 항목 클릭 → End-to-end transaction details 에서 실패 원인 추적

의도적 에러 생성

실패 데이터를 확인하려면 존재하지 않는 endpoint로 요청을 보내세요:

for i in {1..10}; do
  curl -s "http://awesome-apigateway.${INGRESS_IP}.nip.io/api/nonexistent"
done
for /L %i in (1,1,10) do curl -s "http://awesome-apigateway.%INGRESS_IP%.nip.io/api/nonexistent"

참고: Investigate failures, performance, and transactions

  1. Application Insights → Investigate → Search
  2. 시간 범위를 Last 30 minutes로 설정
  3. Event types 필터로 Request, Dependency, Exception, Trace 등 선택
  4. 항목 클릭 → End-to-end transaction details 에서 전체 호출 체인 확인

Transaction Diagnostics

End-to-end transaction details 화면은 Gantt chart 형태로 요청의 전체 흐름을 보여줍니다. 서버 간 텔레메트리를 자동으로 correlation하여 하나의 요청이 여러 서비스를 거치는 과정을 추적할 수 있습니다.

6) Live Metrics (참고)

  1. Application Insights → Investigate → Live Metrics

Live Metrics 미지원 (OTel Collector 경유 시)

Live Metrics(QuickPulse)는 애플리케이션 SDK가 Application Insights에 직접 연결할 때만 동작합니다.
이 Lab에서는 앱 → OTel Collector → Azure Monitor Exporter 경로를 사용하므로 Live Metrics가 표시되지 않습니다.
이는 정상이며, 텔레메트리 데이터는 위의 Performance, Failures, Application Map, Search 등에서 확인할 수 있습니다.
→ Live Metrics 지원 조건


Part 4: Logs (KQL) 쿼리

Application Insights → Monitoring → Logs 에서 아래 KQL 쿼리를 실행합니다.

데이터 지연

Logs 쿼리 결과는 2~5분 지연이 있을 수 있습니다. 트래픽 생성 후 잠시 대기한 뒤 쿼리를 실행하세요.

서비스별 요청 수

requests
| where timestamp > ago(30m)
| summarize count() by cloud_RoleName
| order by count_ desc

서비스별 평균 응답 시간 (P95 포함)

requests
| where timestamp > ago(30m)
| summarize
    avg_duration = avg(duration),
    p95_duration = percentile(duration, 95),
    request_count = count()
  by cloud_RoleName
| order by avg_duration desc

실패 요청 조회

requests
| where timestamp > ago(1h)
| where success == false
| project timestamp, cloud_RoleName, name, resultCode, duration
| order by timestamp desc

Dependency 호출 분석 (MySQL, Redis 등)

dependencies
| where timestamp > ago(30m)
| summarize
    avg_duration = avg(duration),
    failure_count = countif(success == false),
    total_count = count()
  by target, type
| order by avg_duration desc

참고: Application Insights telemetry data model


(Optional) Part 5: Alert Rule 생성

  1. Application Insights → Monitoring → Alerts → + Create → Alert rule
  2. Condition: Signal = Failed requests, Threshold > 5 (5분 내 실패 5건 이상)
  3. Actions: 이메일 알림 또는 Action Group (실습에서는 생략 가능)
  4. Details: Alert rule name = High Error Rate - Lab92
  5. Review + create

참고: Alerts overview


Verify - Azure Portal

Application Insights (OTel Collector 경유)

메뉴 확인 항목
Overview 요청 수, 실패율, 응답 시간 그래프
Live Metrics OTel Collector 경유 시 미지원 (SDK 직접 연결 필요)
Application Map 서비스 간 의존 관계, 노드별 응답 시간/실패율
Performance Operation별 응답 시간, Dependency 응답 시간
Failures 실패 요청 분류, Exception 목록
Search 개별 텔레메트리 항목 → 클릭 → End-to-end transaction details (Gantt chart + 연관 Trace 로그)
Logs KQL 쿼리 (requests, dependencies, traces 테이블)

Container Insights (AKS Monitoring add-on)

경로 확인 항목
AKS → Monitoring → Insights → Nodes/Controllers/Containers 탭 노드·Pod CPU/Memory 사용률, 상태
AKS → Kubernetes resources → Workloads → Pod 선택 → Live Logs 컨테이너 stdout/stderr 실시간 스트리밍
AKS → Kubernetes resources → Workloads → Pod 선택 → Live Events K8s 이벤트 실시간
Log Analytics Workspace → Logs → ContainerLogV2 Pod stdout/stderr 과거 로그 KQL 쿼리
Log Analytics Workspace → Logs → KubePodInventory Pod 상태 이력, 재시작 이력

두 데이터 소스 연결

  • 앱 에러 분석: Application Insights Search → 항목 클릭 → End-to-end transaction details → 연관 Trace(로그) 확인
  • Pod 로그 연결: ContainerLogV2의 PodName과 Application Insights의 cloud_RoleInstance를 매칭하면 인프라 로그와 앱 텔레메트리를 연결할 수 있습니다

참고: OTel Collector 없이 Azure Monitor로 직접 전송

이 Lab에서는 OTel Collector를 별도 배포하여 Traces/Metrics/Logs를 Azure Monitor로 전송합니다. 하지만 Collector를 거치지 않는 직접 전송 방법도 있습니다.

방법 1 — Application SDK 직접 Exporter

각 언어별 Azure Monitor OpenTelemetry Exporter/Distro를 앱 코드에 추가하면, Application Insights의 Connection String만으로 Collector 없이 직접 전송할 수 있습니다.

언어 패키지
.NET Azure.Monitor.OpenTelemetry.AspNetCore → UseAzureMonitor()
Java Azure Monitor OpenTelemetry Distro (auto-attach)
Node.js @azure/monitor-opentelemetry
Python azure-monitor-opentelemetry-exporter

앱에 APPLICATIONINSIGHTS_CONNECTION_STRING 환경변수를 주입하면 traces, metrics, logs가 Application Insights로 바로 전송됩니다.

참고: Enable Azure Monitor OpenTelemetry

방법 2 — AKS Autoinstrumentation (Preview)

AKS 클러스터 설정에서 Application Monitoring을 활성화하면, Java / Node.js 앱에 대해 코드 수정 없이 자동 계측이 가능합니다 (Preview).

  1. AKS Monitor settings → "Enable support for Autoinstrumentation" 활성화
  2. Application Insights 리소스에 "Enable OTLP Support (Preview)" 켬
  3. Namespace별로 autoinstrumentation 또는 autoconfiguration 선택

별도 Collector 배포 없이, AKS 플랫폼 수준에서 OTel 데이터를 Azure Monitor로 라우팅합니다.

참고: Monitor AKS applications with OTLP (Preview)

Collector 방식과의 비교

항목 OTel Collector (이 Lab) SDK 직접 Exporter AKS Autoinstrumentation
추가 인프라 Collector Pod 필요 없음 없음 (AKS add-on)
코드 변경 앱은 OTLP로 export → Collector가 변환 앱에 SDK/패키지 추가 필요 Java/Node.js는 변경 없음
지원 언어 모든 OTel 호환 언어 .NET, Java, Node.js, Python Java, Node.js (Preview)
유연성 높음 (필터, 샘플링, 멀티 백엔드) 중간 낮음 (플랫폼 관리)
상태 GA (contrib exporter) GA Preview

이 Lab에서 Collector를 사용하는 이유

Collector 방식은 언어에 상관없이 동작하고, 필터링·샘플링·멀티 백엔드 전송 등 유연한 파이프라인 설계가 가능합니다. 운영 환경에서 가장 보편적인 패턴이며, 직접 Exporter나 AKS Autoinstrumentation은 단순한 구성이 필요할 때 적합합니다.


Cleanup

아직 삭제하지 마세요

이 Lab이 AKS 시리즈의 마지막 실습입니다.
Lab 90 · 91 · 92 리소스를 한꺼번에 정리하려면 Custom Lab Cleanup 을 진행하세요.


Terraform Files

파일 역할
versions.tf Terraform / provider 버전 제약
providers.tf azurerm provider
variables.tf prefix, RG, retention 등
main.tf Log Analytics Workspace, Application Insights
outputs.tf workspace name/ID, connection string
terraform.tfvars.example 변수 예시 파일
clusters/az104-aks/otel-collector/otel-collector.yaml OTel Collector Kubernetes 매니페스트 (ConfigMap + Deployment + Service)

수집 경로 정리 — OTel vs Container Insights

같은 logger.info("주문 생성") 호출이 두 경로로 동시에 수집됩니다. 형태와 용도가 다릅니다.

수집 흐름 비교

[OTel 경로]
  앱 logger.info() → Logback 훅 (OTel Agent) → OTLP LogRecord
    → OTel Collector → Application Insights
    → 저장: traces 테이블 (구조화, traceId/spanId 포함)

[Container Insights 경로]
  앱 logger.info() → Logback ConsoleAppender → stdout
    → /var/log/containers/*.log
    → ama-logs DaemonSet → Log Analytics
    → 저장: ContainerLogV2 테이블 (원시 텍스트)

무엇이 어디에 저장되는가

데이터 OTel Collector → APPI Container Insights → LAW 비고
분산 추적 (Span) ✅ requests, dependencies — trace correlation 포함
앱 구조화 로그 ✅ traces — severity, traceId, spanId
앱 stdout 원시 로그 — ✅ ContainerLogV2 텍스트 기반, K8s 메타데이터
앱 메트릭 (Micrometer) ✅ customMetrics — JVM, HTTP 요청 통계
인프라 메트릭 (CPU/Memory) — ✅ Perf, InsightsMetrics 노드·Pod 수준
K8s 인벤토리 (Pod 상태) — ✅ KubePodInventory 재시작, 상태 변경 이력

핵심 차이

비교 항목 OTel (traces 테이블) Container Insights (ContainerLogV2)
trace 연결 ✅ 동일 operation_Id로 Span과 묶임 ❌ 없음
수집 방식 Logback/Log4j 프레임워크 훅 (바이트코드) 노드 파일시스템 /var/log/containers 읽기
구조 구조화 (key-value, severity) 원시 텍스트 한 줄
용도 분산 추적 디버깅, 에러 근본 원인 분석 인프라 운영, Pod 장애 원인 조사
Portal 위치 Application Insights → Search/Performance/Failures AKS → Insights / Live Logs, LAW → Logs

실습에서의 활용

  • "왜 API 응답이 느렸지?" → Application Insights Performance → Span Gantt chart + 연관 로그
  • "Pod이 왜 재시작됐지?" → AKS Live Logs 또는 ContainerLogV2에서 OOM/CrashLoop 원인 확인
  • 두 소스 매칭: ContainerLogV2.PodName ↔ Application Insights cloud_RoleInstance

Troubleshooting

증상 원인 해결
Collector CrashLoop Connection String 누락 Secret 생성 확인: kubectl get secret -n otel-collector
Application Insights 데이터 없음 Exporter 설정 오류 Collector 로그 확인: kubectl logs -n otel-collector deployment/otel-apps
Traces만 보이고 Metrics 없음 Pipeline 설정 누락 config.yaml에서 metrics pipeline 확인
앱 로그에 "connection refused" Collector 미배포 또는 Service DNS 미해결 kubectl get svc -n otel-collector, endpoint 확인
Log Analytics 쿼리 결과 없음 데이터 지연 (최대 5분) 5분 대기 후 재시도
Alert 미발동 Threshold 미달 또는 평가 기간 미경과 Alert condition의 evaluation period, threshold 확인

Cost & Caution

데이터 수집 비용

Log Analytics는 수집량 기반 과금입니다. 실습 후 OTel Collector를 삭제하지 않으면 계속 데이터가 쌓입니다. 실습 종료 시 반드시 terraform destroy와 Collector 정리를 수행하세요.