IMG-LOGO
공지사항 :

Prometheus + Grafana + Alertmanager로 Node, Pod, FastAPI의 CPU와 Memory 모니터링

lmkfox - 2026-09-09 06:53:54 3 Views 0 Comment

Kubernetes 모니터링 실습

Prometheus + Grafana + Alertmanager로 Node, Pod, FastAPI의 CPU와 Memory 모니터링하기

Kubernetes 환경을 운영하다 보면 단순히 Pod가 Running 상태인지 확인하는 것만으로는 부족하다.

예를 들어 다음과 같은 상황을 생각해 보자.

Pod는 Running
하지만 CPU 95%

Pod는 Running
하지만 Memory 90%

Node는 Ready
하지만 Disk 95%

FastAPI는 Running
하지만 API 응답시간 5초

kubectl get pods만 실행해서는 이런 문제를 빠르게 발견하기 어렵다.

그래서 Kubernetes 운영 환경에서는 Monitoring 시스템을 구축해야 한다.

이번 실습에서는 다음과 같은 모니터링 환경을 구축한다.

                         Kubernetes Cluster
                                |
              +-----------------+-----------------+
              |                                   |
              v                                   v
        [ Node / Pod ]                        [ FastAPI ]
              |                                   |
              | Metrics                         Metrics
              |                                   |
              +------------------+----------------+
                                 |
                                 v
                           [ Prometheus ]
                                 |
                     +-----------+-----------+
                     |                       |
                     v                       v
                [ Grafana ]            [ Alertmanager ]
                     |                       |
                     v                       v
                  Dashboard             장애 알림

이번 실습의 목표는 다음과 같다.

1. Prometheus 설치
2. Grafana 설치
3. Alertmanager 구성
4. Kubernetes Node 모니터링
5. Pod CPU/Memory 모니터링
6. FastAPI 모니터링
7. Grafana Dashboard 구성
8. CPU/Memory Alert 설정
9. Pod 장애 Alert
10. Alertmanager 알림 확인
11. 실제 장애 테스트

1. Kubernetes 모니터링 구조 이해

먼저 각각의 역할을 이해해야 한다.

Prometheus

Prometheus는 Metric 수집 및 저장 시스템이다.

예를 들어:

CPU 사용률
Memory 사용률
Pod 개수
HTTP 요청 수
HTTP 응답 시간
Network Traffic

등의 숫자 데이터를 수집한다.

Node
 |
 v
Metric
 |
 v
Prometheus

2. Grafana

Grafana는 Prometheus의 데이터를 사람이 보기 편하게 보여주는 시각화 시스템이다.

Prometheus에 저장된:

CPU
Memory
Network
Request
Latency

등을 그래프로 표시할 수 있다.

구조:

Prometheus
    |
    | Query
    v
Grafana
    |
    v
Dashboard

예를 들어:

CPU Usage
100% |             /\
 80% |       /\    /  \
 60% |  /\  /  \__/    \
 40% |_/  \/
 20% |
  0% +---------------------
       10 20 30 40 50 60
             Time

처럼 시간에 따른 변화를 확인할 수 있다.


3. Alertmanager

Prometheus가 장애 조건을 감지하면 Alertmanager가 알림을 관리한다.

Prometheus
    |
    | Alert
    v
Alertmanager
    |
    +---- Email
    |
    +---- Slack
    |
    +---- Webhook
    |
    +---- PagerDuty

예를 들어:

CPU > 80%
5분 이상 지속

이면:

[ALERT]
FastAPI Pod CPU usage is high

와 같은 알림을 보낼 수 있다.


4. Kubernetes에서 사용하는 대표적인 모니터링 구성

이번 실습에서는 직접 모든 컴포넌트를 하나씩 설치하기보다 Kubernetes 환경에서 많이 사용하는 kube-prometheus-stack을 사용한다.

구성:

kube-prometheus-stack
       |
       +-- Prometheus
       |
       +-- Grafana
       |
       +-- Alertmanager
       |
       +-- Node Exporter
       |
       +-- kube-state-metrics

각각의 역할은 다음과 같다.

구성요소 역할
Prometheus Metric 수집/저장
Grafana Dashboard
Alertmanager Alert 전달
Node Exporter Node OS Metric
kube-state-metrics Kubernetes Object 상태
Prometheus Operator Prometheus 관련 리소스 관리

5. Helm Repository 추가

이번 실습에서는 Helm을 이용한다.

먼저 Repository를 추가한다.

helm repo add prometheus-community \
  https://prometheus-community.github.io/helm-charts

Repository 업데이트:

helm repo update

Chart 확인:

helm search repo prometheus-community

6. Monitoring Namespace 생성

모니터링 시스템은 별도의 Namespace에 설치한다.

kubectl create namespace monitoring

확인:

kubectl get namespace

구조:

Kubernetes Cluster
│
├── myapp
│   ├── FastAPI
│   ├── PostgreSQL
│   ├── Redis
│   └── Nginx
│
└── monitoring
    ├── Prometheus
    ├── Grafana
    ├── Alertmanager
    ├── Node Exporter
    └── kube-state-metrics

운영 환경에서는 애플리케이션과 모니터링 시스템을 분리해서 관리하는 것이 좋다.


7. kube-prometheus-stack 설치

가장 간단한 방법은 다음과 같다.

helm install monitoring \
  prometheus-community/kube-prometheus-stack \
  -n monitoring

설치 확인:

kubectl get pods -n monitoring

정상적으로 설치되면 대략 다음과 같은 Pod가 나타난다.

NAME
alertmanager-monitoring-kube-prometheus-alertmanager-0
monitoring-grafana-xxxx
monitoring-kube-prometheus-operator-xxxx
monitoring-kube-state-metrics-xxxx
monitoring-prometheus-node-exporter-xxxx
prometheus-monitoring-kube-prometheus-prometheus-0

모두 Running 또는 정상적인 상태인지 확인한다.


8. 설치된 리소스 확인

kubectl get all -n monitoring

Service:

kubectl get svc -n monitoring

Prometheus:

kubectl get prometheus -n monitoring

Alertmanager:

kubectl get alertmanager -n monitoring

ServiceMonitor:

kubectl get servicemonitor -A

9. Prometheus 접속

학습 환경에서는 Port Forward를 사용하면 편하다.

Prometheus Service를 확인한다.

kubectl get svc -n monitoring

Prometheus Service를 Port Forward:

kubectl port-forward \
  svc/monitoring-kube-prometheus-prometheus \
  9090:9090 \
  -n monitoring

브라우저에서:

http://localhost:9090

으로 접속한다.

Prometheus 화면이 나오면 정상이다.


10. Prometheus에서 Metric 확인

Prometheus에는 Query를 입력할 수 있다.

예를 들어 CPU 관련 Metric을 확인할 수 있다.

node_cpu_seconds_total

Memory:

node_memory_MemAvailable_bytes

Kubernetes Pod 관련 Metric:

kube_pod_info

Node:

kube_node_info

Prometheus의 핵심은 PromQL이라는 Query Language다.


11. PromQL이 중요한 이유

운영 환경에서는 단순히 Metric을 보는 것보다 원하는 조건을 계산해야 한다.

예를 들어 CPU 사용률을 계산할 수 있다.

100 *
(
  1 -
  avg by(instance)(
    rate(node_cpu_seconds_total{
      mode="idle"
    }[5m])
  )
)

이 Query는 Node의 CPU 사용률을 계산하는 데 사용할 수 있다.

결과:

node01    23%
node02    61%
node03    82%

처럼 확인할 수 있다.


12. Node Memory 모니터링

Node의 Memory 사용률:

100 *
(
  1 -
  node_memory_MemAvailable_bytes
  /
  node_memory_MemTotal_bytes
)

예:

node01    42%
node02    71%
node03    91%

운영에서는 특정 임계치를 넘는 경우 Alert를 발생시킬 수 있다.


13. Pod CPU 모니터링

Pod CPU 사용량:

sum by (namespace, pod) (
  rate(container_cpu_usage_seconds_total{
    container!="",
    container!="POD"
  }[5m])
)

결과:

myapp/backend-xxxx    0.25 CPU
myapp/backend-yyyy    0.63 CPU
myapp/nginx-xxxx      0.04 CPU

이렇게 어떤 Pod가 CPU를 많이 사용하는지 확인할 수 있다.


14. Pod Memory 모니터링

sum by (namespace, pod) (
  container_memory_working_set_bytes{
    container!="",
    container!="POD"
  }
)

Memory를 MiB 단위로 보고 싶다면:

sum by (namespace, pod) (
  container_memory_working_set_bytes{
    container!="",
    container!="POD"
  }
) / 1024 / 1024

예:

backend-xxxx    245 MiB
backend-yyyy    310 MiB
nginx-xxxx       52 MiB

15. Grafana 접속

Grafana Service를 확인한다.

kubectl get svc -n monitoring

Port Forward:

kubectl port-forward \
  svc/monitoring-grafana \
  3000:80 \
  -n monitoring

브라우저:

http://localhost:3000

으로 접속한다.


16. Grafana 관리자 비밀번호 확인

설치된 Secret을 확인한다.

kubectl get secret \
  monitoring-grafana \
  -n monitoring

비밀번호를 확인하는 방법은 설치 Chart의 설정에 따라 Secret 이름과 Key가 달라질 수 있으므로 실제 Secret 구조를 먼저 확인한다.

kubectl get secret monitoring-grafana \
  -n monitoring \
  -o jsonpath="{.data.admin-password}" | base64 -d

사용자 이름은 일반적으로:

admin

이다.

환경에 따라 초기 인증정보 설정 방식을 명시적으로 관리하는 것이 좋다.


17. Grafana에서 Prometheus 연결 확인

Grafana에 로그인한 뒤:

Connections
    |
    v
Data Sources
    |
    v
Prometheus

를 확인한다.

kube-prometheus-stack을 정상적으로 설치했다면 Prometheus Data Source가 함께 구성되는 경우가 많다.

Data Source의 연결 테스트를 수행한다.

Successfully queried the Prometheus API.

와 같은 정상 응답을 확인한다.


18. Kubernetes Dashboard 구성

Grafana에서는 Dashboard를 이용해 Kubernetes 상태를 시각화할 수 있다.

대표적으로:

Cluster
Node
Namespace
Pod
Deployment
CPU
Memory
Network

등을 한 화면에서 볼 수 있다.

운영 환경에서는 Dashboard를 다음과 같이 구성하는 것이 좋다.

+------------------------------------------------+
| Kubernetes Cluster                             |
+------------------------------------------------+
| Nodes: 3     Pods: 47     CPU: 42%   MEM: 61% |
+------------------------------------------------+
| Node CPU                                       |
| ███████████████                               |
+------------------------------------------------+
| Node Memory                                    |
| ███████████████████                           |
+------------------------------------------------+
| Pod CPU                                        |
| backend-1    ███████                          |
| backend-2    █████████                        |
+------------------------------------------------+

19. FastAPI 자체를 모니터링하기

Node와 Kubernetes Metric만으로는 애플리케이션 상태를 완전히 알 수 없다.

예를 들어:

CPU 30%
Memory 40%
Pod Running

이어도 API가 느릴 수 있다.

따라서 FastAPI 자체에서 Metric을 제공하도록 구성하는 것이 좋다.

대표적으로 Prometheus Python Client를 사용할 수 있다.

requirements.txt:

prometheus-client

20. FastAPI Metric Endpoint

예:

from fastapi import FastAPI
from prometheus_client import Counter, generate_latest
from starlette.responses import Response

app = FastAPI()

REQUEST_COUNT = Counter(
    "fastapi_requests_total",
    "Total FastAPI requests"
)


@app.get("/")
def root():
    REQUEST_COUNT.inc()

    return {
        "message": "Hello Kubernetes"
    }


@app.get("/metrics")
def metrics():
    return Response(
        generate_latest(),
        media_type="text/plain"
    )

이제:

/metrics

로 접속하면 Prometheus가 수집할 수 있는 Metric을 확인할 수 있다.


21. FastAPI에서 수집할 수 있는 Metric

예를 들어:

fastapi_requests_total

을 이용하면 전체 요청 수를 확인할 수 있다.

여기에 다음과 같은 Metric을 추가하면 더욱 유용하다.

HTTP Request Count
HTTP Request Duration
HTTP Error Count
Active Requests
Database Connection
Redis Connection

실제 운영에서는 단순한 서버 자원보다 서비스 상태를 나타내는 Application Metric이 매우 중요하다.


22. ServiceMonitor

kube-prometheus-stack에서는 ServiceMonitor를 이용해 애플리케이션 Metric을 Prometheus가 자동으로 수집하도록 구성할 수 있다.

예:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor

metadata:
  name: fastapi
  namespace: myapp

  labels:
    release: monitoring

spec:
  selector:
    matchLabels:
      app: backend

  endpoints:
    - port: http
      path: /metrics
      interval: 15s

이렇게 하면:

FastAPI
   |
   | /metrics
   v
Service
   |
   v
ServiceMonitor
   |
   v
Prometheus

구조가 만들어진다.

단, Service의 포트 이름과 ServiceMonitor의 port 값이 정확히 일치해야 한다.


23. Prometheus에서 FastAPI Metric 확인

Prometheus에서:

fastapi_requests_total

을 실행한다.

정상적으로 수집되고 있다면:

fastapi_requests_total{...} 1523

처럼 결과가 나타난다.

이제 Kubernetes Metric뿐만 아니라 실제 애플리케이션 Metric까지 Prometheus에서 관리할 수 있다.


24. FastAPI 요청률 확인

초당 요청량을 확인하려면:

rate(fastapi_requests_total[5m])

예:

0.5 requests/sec

또는:

15 requests/sec

등으로 확인할 수 있다.

이를 Grafana에서 그래프로 표현하면 트래픽 증가 여부를 쉽게 파악할 수 있다.


25. FastAPI 장애율 모니터링

애플리케이션에서 HTTP 상태 코드별 Counter를 관리한다면 오류율도 계산할 수 있다.

예:

rate(fastapi_requests_total{status=~"5.."}[5m])

전체 요청 대비 오류율:

(
  rate(fastapi_requests_total{status=~"5.."}[5m])
/
  rate(fastapi_requests_total[5m])
) * 100

예:

HTTP 5xx Error Rate = 8.2%

운영에서는 CPU보다 이런 지표가 더 중요한 경우가 많다.


26. Alert Rule 만들기

이제 장애 알림을 만들어 보자.

예를 들어:

Node CPU > 80%
5분 이상

이면 Alert를 발생시키도록 설정한다.

PrometheusRule:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule

metadata:
  name: myapp-alerts
  namespace: monitoring

  labels:
    release: monitoring

spec:
  groups:

    - name: node.rules

      rules:

        - alert: HighNodeCPU

          expr: |
            100 *
            (
              1 -
              avg by(instance)(
                rate(node_cpu_seconds_total{
                  mode="idle"
                }[5m])
              )
            ) > 80

          for: 5m

          labels:
            severity: warning

          annotations:
            summary: "Node CPU usage is high"
            description: "Node CPU usage has exceeded 80% for 5 minutes."

27. Pod Memory Alert

Pod Memory가 특정 수준을 초과했는지 확인할 수도 있다.

예:

- alert: HighPodMemory

  expr: |
    (
      sum by(namespace, pod) (
        container_memory_working_set_bytes{
          container!="",
          container!="POD"
        }
      )
      /
      sum by(namespace, pod) (
        kube_pod_container_resource_limits{
          resource="memory"
        }
      )
    ) * 100 > 80

  for: 5m

  labels:
    severity: warning

  annotations:
    summary: "Pod memory usage is high"

운영 환경에서는 실제 리소스 설정과 Metric label 구조에 맞게 PromQL을 검증해야 한다.


28. Pod 장애 Alert

Pod가 예상보다 적게 실행되는 상황도 감지할 수 있다.

예:

kube_deployment_status_replicas_available
<
kube_deployment_spec_replicas

이런 조건을 Alert Rule로 구성할 수 있다.

Deployment desired
        |
        v
       3 Pod

Available
        |
        v
       2 Pod

       ↓

Alert

29. Alert 상태

Prometheus Alert는 일반적으로 다음 상태를 거친다.

Inactive
   |
   v
Pending
   |
   | 조건 지속
   v
Firing

예를 들어:

CPU > 80%

조건이 순간적으로 발생했다고 바로 알림을 보내는 것이 아니라:

for: 5m

처럼 일정 시간 지속되는지를 확인할 수 있다.

이렇게 해야 순간적인 CPU Spike 때문에 불필요한 알림이 발생하는 것을 줄일 수 있다.


30. Alertmanager 역할

Prometheus가 Alert를 감지하면 Alertmanager로 전달한다.

Prometheus
     |
     | Firing
     v
Alertmanager
     |
     +------ Email
     |
     +------ Slack
     |
     +------ Webhook

Alertmanager는 다음과 같은 작업을 담당한다.

Grouping
Routing
Silencing
Inhibition
Notification

예를 들어 Node 하나가 장애가 나서 20개의 Pod가 동시에 장애가 발생할 수 있다.

이때 Alert를 20개 따로 보내는 대신 하나의 그룹으로 묶어 알림을 줄일 수 있다.


31. Alertmanager 설정 개념

기본적인 설정은 다음과 같은 구조를 갖는다.

route:
  group_by:
    - alertname
    - namespace

  receiver: default

receivers:

  - name: default

    # email/slack/webhook 설정

중요한 것은 어떤 Alert를 어디로 보낼 것인지다.

예:

severity=warning
       |
       v
Slack

severity=critical
       |
       v
Slack + Email

같은 Routing을 구성할 수 있다.


32. 운영 환경 Alert 설계

모든 것을 Alert로 만들면 오히려 운영자가 알림을 무시하게 된다.

따라서 중요도를 나누는 것이 좋다.

INFO
 |
 +-- 일반적인 상태 변화

WARNING
 |
 +-- CPU 80%
 +-- Memory 80%

CRITICAL
 |
 +-- CPU 95%
 +-- Pod 전체 장애
 +-- API 5xx 급증
 +-- Node Down

예:

CPU 81%
→ WARNING

CPU 96%
→ CRITICAL

처럼 운영 정책을 만들 수 있다.


33. 실제 장애 테스트

이제 실제 장애를 만들어 본다.

먼저 FastAPI Pod를 확인한다.

kubectl get pods -n myapp

Pod를 삭제한다.

kubectl delete pod <backend-pod> -n myapp

Deployment가 정상적으로 관리하고 있다면 새로운 Pod가 생성된다.

kubectl get pods -n myapp -w

이 과정에서:

Pod Deleted
     |
     v
Deployment 감지
     |
     v
New Pod 생성
     |
     v
Readiness 성공
     |
     v
Service 연결

이 발생한다.


34. CrashLoopBackOff 테스트

FastAPI의 실행 명령을 잘못 설정해 배포해 보자.

Wrong command
      |
      v
Container Start
      |
      v
Application Exit
      |
      v
Restart
      |
      v
Restart
      |
      v
CrashLoopBackOff

확인:

kubectl get pods -n myapp

그리고:

kubectl logs <pod> -n myapp

Prometheus에서는 Pod 상태 관련 Metric을 통해 이상 상태를 감지할 수 있다.


35. CPU 부하 테스트

CPU를 의도적으로 증가시키는 테스트도 할 수 있다.

예를 들어 테스트용 Pod에서 CPU 작업을 수행한다.

kubectl run cpu-test \
  --image=busybox \
  --restart=Never \
  -n myapp \
  -- sh -c "while true; do :; done"

단, 실제 운영 Namespace에서 무분별하게 실행하지 말고 반드시 테스트 환경에서 수행한다.

삭제:

kubectl delete pod cpu-test -n myapp

CPU 사용량:

kubectl top pod -n myapp

Prometheus에서도 CPU 증가를 확인할 수 있다.


36. HPA와 Prometheus의 차이

이 부분은 매우 중요하다.

HPA:

Metric 증가
   |
   v
Pod 개수 증가

Prometheus:

Metric 수집
   |
   v
저장 / 분석
   |
   v
Dashboard / Alert

즉:

HPA = 자동 확장

Prometheus = 관측 및 분석

이다.

둘은 목적이 다르다.


37. Grafana에서 운영 Dashboard 구성

운영 환경에서는 하나의 Dashboard에 너무 많은 정보를 넣지 않는 것이 좋다.

다음과 같이 나누는 것이 좋다.

Cluster Dashboard

Node CPU
Node Memory
Node Network
Node Status

Kubernetes Dashboard

Pod
Deployment
Replica
Restart
Namespace

Application Dashboard

Request/sec
Response Time
5xx Error
Active Request

Database Dashboard

PostgreSQL Connections
Query
Transaction
Cache
Storage

Redis Dashboard

Memory
Connected Clients
Commands
Hit Rate

이렇게 구성하면 장애 발생 시 빠르게 원인을 좁힐 수 있다.


38. Kubernetes 운영자가 자주 확인해야 하는 지표

Node

CPU
Memory
Disk
Network
Load

Pod

CPU
Memory
Restart
Status
Network

Application

Request Rate
Latency
Error Rate
Availability

Database

Connection
Query
Lock
Transaction
Storage

39. 로그와 Metric을 함께 봐야 한다

운영 장애에서 매우 중요한 원칙이다.

Metric만 보면:

CPU 95%

라는 사실은 알 수 있다.

하지만 왜 CPU가 95%인지 알기 어렵다.

로그를 함께 보면:

ERROR database timeout
ERROR retry
ERROR request failed

같은 원인을 찾을 수 있다.

따라서:

Metric
  +
Log
  +
Trace

를 함께 보는 것이 현대적인 Observability의 기본 구조다.


40. Monitoring 시스템 자체도 모니터링해야 한다

중요한 부분이다.

다음과 같은 상황을 생각해 보자.

FastAPI 장애
     |
     v
Prometheus도 장애
     |
     v
Alert 발생 안 함

이러면 장애를 감지할 수 없다.

따라서 Monitoring 시스템 자체의 상태도 확인해야 한다.

kubectl get pods -n monitoring

Prometheus:

kubectl get prometheus -n monitoring

Alertmanager:

kubectl get alertmanager -n monitoring

Grafana:

kubectl get deployment -n monitoring

모니터링 시스템 자체도 중요한 운영 대상이다.


41. Prometheus Storage

Prometheus는 Metric을 저장하기 때문에 운영 환경에서는 Storage도 중요하다.

Prometheus
    |
    v
PersistentVolumeClaim
    |
    v
Storage

Helm values에서 Prometheus Storage를 설정할 수 있다.

예:

prometheus:
  prometheusSpec:
    storageSpec:
      volumeClaimTemplate:
        spec:
          resources:
            requests:
              storage: 50Gi

운영 환경에서는 Metric 보존 기간과 Storage 용량을 함께 고려해야 한다.


42. Grafana도 Persistence 고려

Grafana에서 Dashboard 등을 직접 관리한다면 Persistence를 고려한다.

Grafana
   |
   v
PVC

또는 Dashboard와 설정을 코드로 관리하여 재배포 시 자동으로 복구되도록 구성할 수도 있다.

운영 환경에서는 Dashboard를 사람이 수동으로만 관리하지 않고 Git을 이용해 버전 관리하는 방식도 유용하다.


43. Helm으로 Monitoring 환경 관리

Monitoring 역시 Helm으로 관리할 수 있다.

예:

monitoring/
├── values-dev.yaml
├── values-prod.yaml
└── Chart configuration

개발:

Prometheus
  Storage 10Gi

Grafana
  Resource 최소

운영:

Prometheus
  Storage 100Gi+

Grafana
  Replica / Resource 증가

Alertmanager
  운영 알림

환경별 설정을 분리할 수 있다.


44. 실제 운영 구조

지금까지 구축한 시스템을 합치면 다음과 같은 구조가 된다.

                             Internet
                                |
                                v
                         +-------------+
                         |   Ingress   |
                         +-------------+
                                |
                                v
                            Nginx
                                |
                                v
                           FastAPI
                         /    |    \
                        /     |     \
                       v      v      v
                  PostgreSQL Redis  Metrics
                                      |
                                      v
                                 Prometheus
                                /          \
                               /            \
                              v              v
                         Grafana       Alertmanager
                              |              |
                              v              v
                         Dashboard      Notifications

그리고 Kubernetes 자체도 모니터링한다.

                 Kubernetes Cluster
                        |
          +-------------+-------------+
          |                           |
          v                           v
       Nodes                         Pods
          |                           |
          +-------------+-------------+
                        |
                        v
                   Prometheus

45. 운영 장애 대응 프로세스

실제 시스템 장애가 발생하면 다음과 같은 흐름으로 접근할 수 있다.

Alert 발생
    |
    v
Grafana Dashboard 확인
    |
    v
Node 문제?
    |
    +---- YES ---> Node CPU / Memory / Disk 확인
    |
    NO
    |
    v
Pod 문제?
    |
    +---- YES ---> Pod 상태 / Restart / Logs
    |
    NO
    |
    v
Application 문제?
    |
    +---- YES ---> Request / Latency / 5xx
    |
    NO
    |
    v
DB / Redis 확인

이렇게 Metric → Kubernetes → Application → Database 순서로 범위를 좁혀가는 것이 좋다.


46. 시스템 엔지니어 관점에서 가장 중요한 Metric

모든 Metric을 수집한다고 좋은 모니터링 시스템이 되는 것은 아니다.

가장 중요한 것은 장애와 직접 연결되는 Metric이다.

예를 들어 FastAPI 서비스라면:

Availability
Request Rate
Latency
Error Rate

가 중요하다.

이를 흔히:

Golden Signals

관점에서 생각할 수 있다.

대표적으로:

Latency
Traffic
Errors
Saturation

을 확인한다.


47. Monitoring 구축 후 확인할 체크리스트

Kubernetes

[ ] Node Metric 수집
[ ] Pod CPU 수집
[ ] Pod Memory 수집
[ ] Pod Restart 확인
[ ] Deployment 상태 확인

FastAPI

[ ] /metrics API
[ ] Request Count
[ ] Request Rate
[ ] Error Rate
[ ] Response Time

Grafana

[ ] Prometheus Data Source
[ ] Cluster Dashboard
[ ] Node Dashboard
[ ] Pod Dashboard
[ ] Application Dashboard

Alertmanager

[ ] CPU Alert
[ ] Memory Alert
[ ] Pod 장애 Alert
[ ] Application Error Alert
[ ] Notification 테스트

Storage

[ ] Prometheus PVC
[ ] Grafana Persistence
[ ] Retention 설정

48. 최종 정리

이번 실습에서는 Kubernetes 환경에 다음과 같은 운영 모니터링 시스템을 구축했다.

+------------------------------------------------+
|                Monitoring Stack                |
+------------------------------------------------+
|                                                |
|  Prometheus                                    |
|      |                                         |
|      +---- Node Metric                         |
|      +---- Pod Metric                          |
|      +---- Kubernetes Metric                   |
|      +---- FastAPI Metric                      |
|                                                |
|  Grafana                                       |
|      |                                         |
|      +---- Dashboard                           |
|                                                |
|  Alertmanager                                  |
|      |                                         |
|      +---- Warning                             |
|      +---- Critical                            |
|      +---- Notification                        |
|                                                |
+------------------------------------------------+

전체 서비스 구조는 다음과 같다.

Internet
   |
   v
Ingress
   |
   v
Nginx
   |
   v
FastAPI
   |
   +------------+
   |            |
   v            v
PostgreSQL    Redis
   |
   v
  PVC


Kubernetes
   |
   +---- Node
   +---- Pod
   +---- Service
   +---- Deployment
          |
          v
      Prometheus
       /       \
      v         v
  Grafana   Alertmanager

여기서 가장 중요한 개념을 정리하면 다음과 같다.

기술 핵심 역할
Prometheus Metric 수집 및 저장
PromQL Metric 조회 및 분석
Grafana Metric 시각화
Alertmanager 장애 알림 관리
Node Exporter Node OS Metric
kube-state-metrics Kubernetes 상태 Metric
ServiceMonitor 애플리케이션 Metric 수집
HPA Pod 자동 확장
Helm 배포 및 설정 관리

특히 다음 네 가지를 구분해서 기억해야 한다.

Prometheus
→ 무엇이 발생하고 있는가?

Grafana
→ 그것을 어떻게 보기 쉽게 표현할 것인가?

Alertmanager
→ 문제가 발생하면 누구에게 어떻게 알려줄 것인가?

HPA
→ 부하가 증가하면 Pod를 어떻게 자동으로 늘릴 것인가?

이 네 가지가 결합되면 Kubernetes 환경은 단순히 애플리케이션을 실행하는 플랫폼에서 상태를 관찰하고, 장애를 감지하고, 자동으로 대응할 수 있는 운영 플랫폼으로 발전한다.


댓글