Kubernetes 기반 Redis 클러스터 구축 및 Prometheus와 Grafana를 활용한 통합 모니터링 시스템 구성

1. Kubernetes 환경에서의 Redis 클러스터 배포 및 데이터 영속화

Kubernetes 상에서 고가용성을 보장하는 Redis 클러스터를 구축하기 위해 NFS 기반의 StorageClass를 활용하여 데이터를 영속적으로 관리하는 방법을 설명합니다.

1.1 NFS 백엔드 스토리지 준비

데이터 저장을 위한 NFS 디렉토리를 생성하고 공유 설정을 진행합니다.

# 데이터 저장용 디렉토리 생성
mkdir -pv /storage/redis-vol/node{0..5}

# NFS 공유 설정
echo "/storage/redis-vol *(rw,no_root_squash)" >> /etc/exports
systemctl restart nfs-server

1.2 Redis 설정 관리를 위한 ConfigMap 생성

클러스터 노드들이 공통으로 사용할 redis.conf 파일을 정의하고 이를 Kubernetes ConfigMap으로 등록합니다.

# redis.conf 작성
cat <<EOF > redis-config.conf
bind 0.0.0.0
port 6379
cluster-enabled yes
cluster-config-file /var/lib/redis/nodes.conf
cluster-node-timeout 5000
dir /var/lib/redis
appendonly yes
protected-mode no
requirepass "securepassword"
masterauth "securepassword"
EOF

# ConfigMap 생성 (네임스페이스: redis-stack)
kubectl create ns redis-stack
kubectl create configmap redis-cfg --from-file=redis.conf=redis-config.conf -n redis-stack

1.3 Redis 클러스터 워크로드 배포 (StatefulSet)

데이터 무결성을 위해 StatefulSet을 사용하여 6개의 복제본을 생성합니다. 각 파드는 개별적인 PVC를 통해 데이터를 저장합니다.

apiVersion: v1
kind: Service
metadata:
  name: redis-svc
  namespace: redis-stack
spec:
  clusterIP: None
  ports:
  - port: 6379
    name: redis
  selector:
    app: redis-cluster
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis-node
  namespace: redis-stack
spec:
  serviceName: redis-svc
  replicas: 6
  selector:
    matchLabels:
      app: redis-cluster
  template:
    metadata:
      labels:
        app: redis-cluster
    spec:
      containers:
      - name: redis
        image: redis:7.2-alpine
        command: ["redis-server", "/etc/redis/redis.conf"]
        ports:
        - containerPort: 6379
          name: redis
        - containerPort: 16379
          name: cluster
        volumeMounts:
        - name: conf
          mountPath: /etc/redis
        - name: data
          mountPath: /var/lib/redis
      volumes:
      - name: conf
        configMap:
          name: redis-cfg
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: nfs-client
      resources:
        requests:
          storage: 2Gi

1.4 클러스터 초기화 및 데이터 검증

파드가 정상 기동되면 redis-cli를 사용하여 클러스터를 구성합니다.

# 클러스터 구성 명령 (각 파드의 IP를 확인하여 실행)
kubectl exec -it redis-node-0 -n redis-stack -- redis-cli -a securepassword --cluster create \
$(kubectl get pods -l app=redis-cluster -n redis-stack -o jsonpath='{range .items[*]}{.status.podIP}:6379 {end}') \
--cluster-replicas 1

데이터 적재 테스트를 위한 Python 스크립트 예시입니다.

from rediscluster import RedisCluster

def check_redis_cluster():
    nodes = [{"host": "redis-node-0.redis-svc.redis-stack.svc.cluster.local", "port": "6379"}]
    try:
        sdk = RedisCluster(startup_nodes=nodes, decode_responses=True, password='securepassword')
        for idx in range(100):
            sdk.set(f"user:{idx}", f"data_{idx}")
        print("Data insertion completed.")
    except Exception as err:
        print(f"Connection failed: {err}")

if __name__ == "__main__":
    check_redis_cluster()

2. Prometheus 아키텍처 및 데이터 수집 메커니즘

Prometheus는 시계열 데이터베이스(TSDB)를 기반으로 하는 오픈 소스 모니터링 시스템입니다.

2.1 핵심 구성 요소

  • Prometheus Server: 데이터를 수집(Scraping)하고 저장하며, PromQL을 통해 쿼리를 처리합니다.
  • Exporters: HTTP 엔드포인트를 통해 하드웨어나 소프트웨어의 메트릭을 노출합니다. (예: node_exporter)
  • Pushgateway: 단기 작업(Batch Job)의 메트릭을 수집하기 위한 중간 대리자입니다.
  • Alertmanager: 정의된 규칙에 따라 경고를 발생시키고 외부로 알림을 전송합니다.

2.2 데이터 수집 흐름

  1. 서비스 디스커버리 또는 정적 설정을 통해 타겟 대상을 확인합니다.
  2. 설정된 주기(Scrape Interval)에 따라 HTTP GET 요청을 타겟에 전송합니다.
  3. 타겟으로부터 텍스트 기반의 메트릭 데이터를 수집하여 TSDB에 저장합니다.
  4. 사용자는 Grafana 또는 PromQL 쿼리를 통해 데이터를 시각화하거나 분석합니다.

3. Prometheus 및 Node Exporter 바이너리 배포

시스템 수준의 자원 모니터링을 위해 직접 바이너리 형태로 설치하는 방법입니다.

3.1 Prometheus 서버 설치

# 바이너리 다운로드 및 압축 해제
tar -xvf prometheus-*.linux-amd64.tar.gz -C /opt/
ln -s /opt/prometheus-*.linux-amd64 /opt/prometheus

# systemd 서비스 등록
cat <<EOF > /etc/systemd/system/prometheus.service
[Unit]
Description=Prometheus
After=network.target

[Service]
Type=simple
ExecStart=/opt/prometheus/prometheus --config.file=/opt/prometheus/prometheus.yml --storage.tsdb.path=/opt/prometheus/data
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl enable --now prometheus

3.2 Node Exporter 설치 및 정적 타겟 설정

모니터링 대상 노드에 node_exporter를 설치하여 시스템 메트릭을 추출합니다.

# prometheus.yml 설정 수정
scrape_configs:
  - job_name: 'node-monitoring'
    static_configs:
      - targets: ['10.0.0.11:9100', '10.0.0.12:9100']

4. PromQL 및 데이터 유형 분석

Prometheus는 실시간으로 시계열 데이터를 쿼리하고 집계할 수 있는 PromQL(Prometheus Query Language)을 제공합니다.

4.1 메트릭 타입

  • Counter: 누적 카운터로 값이 증가만 함 (예: 전체 요청 수).
  • Gauge: 현재 시점의 값을 측정하며 증감이 가능함 (예: 메모리 사용량).
  • Histogram/Summary: 관측값의 분포를 확인하기 위해 버킷별로 저장함 (예: 응답 지연 시간).

4.2 주요 쿼리 예시

# 최근 5분간의 CPU 사용율 계산 (1분 평균)
1 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])))

# 사용 가능한 메모리 비율 계산
(node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100

# 특정 정규 표현식을 사용한 타겟 필터링
node_load1{instance=~"web-.*"}

5. Pushgateway를 이용한 커스텀 데이터 수집

배치 프로그램이나 짧은 시간 실행되는 스크립트의 데이터를 수집할 때 사용합니다.

# 커스텀 메트릭 푸시 스크립트 (Bash)
#!/bin/bash
instance_ip=$(hostname -I | awk '{print $1}')
active_users=$(who | wc -l)

echo "system_active_users $active_users" | \
curl --data-binary @- http://pushgateway.local:9091/metrics/job/user_stats/instance/$instance_ip

6. Prometheus Federation(연합) 구성

여러 하위 Prometheus 서버의 데이터를 상위 계층의 서버로 통합하는 구조입니다.

# 메인 Prometheus 서버의 prometheus.yml 설정
scrape_configs:
  - job_name: 'federation-global'
    honor_labels: true
    metrics_path: '/federate'
    params:
      'match[]':
        - '{job="node-monitoring"}'
        - '{__name__=~"job:.*"}'
    static_configs:
      - targets:
        - 'sub-prometheus-01:9090'
        - 'sub-prometheus-02:9090'

태그: kubernetes Redis-Cluster prometheus Grafana PromQL

6월 1일 12:08에 게시됨