본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Prometheus와 Grafana로 메트릭 모니터링

원문 보기 위키 갱신

Prometheus와 Grafana로 메트릭 모니터링 (Monitor metrics with Prometheus and Grafana)

이 문서에서는 Kubernetes 환경에서 Kong Gateway의 Prometheus 메트릭을 Grafana로 모니터링하는 방법을 알아봐요. Kong Gateway Helm 차트로 servicemonitor 리소스를 배포하고, KongClusterPlugin을 사용해 클러스터의 모든 서비스에 prometheus 플러그인을 적용하는 과정을 단계별로 안내해요. 데모 서비스 배포와 트래픽 생성부터 Grafana 대시보드에서 지연 시간, 에러율, 요청 처리량 같은 메트릭을 확인하는 방법까지 함께 살펴봐요

출처: 문서

본문

TL;DR

Grafana를 사용해서 Kong Gateway Prometheus 메트릭을 어떻게 모니터링하나요? Kong Gateway Helm 차트를 사용해 servicemonitor Kubernetes 리소스를 배포한 다음, KongClusterPlugin을 사용해 클러스터의 모든 Service에 prometheus 플러그인을 설정해요.

전제 조건

Konnect 배포: Kong Konnect

Konnect 계정이 없다면, 온보딩 마법사를 통해 빠르게 시작할 수 있어요.

  1. 이 튜토리얼을 완료하려면 다음 Konnect 항목들이 필요해요:

    • 개인 액세스 토큰(PAT): Konnect PAT 페이지를 열고 Generate Token을 선택해서 새 개인 액세스 토큰을 만들어요.
  2. 개인 액세스 토큰을 환경 변수로 설정해요:

    export KONNECT_TOKEN='YOUR KONNECT TOKEN'
    

Gateway API 활성화

  1. Kong Ingress Controller를 설치하기 전에 Gateway API CRD를 설치해요.

    kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/standard-install.yaml
    

    {: data-test-prereq="block" }

  2. 사용할 Gateway와 GatewayClass 인스턴스를 만들어요.

    echo "
    apiVersion: v1
    kind: Namespace
    metadata:
      name: kong
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: GatewayClass
    metadata:
      name: kong
      annotations:
        konghq.com/gatewayclass-unmanaged: 'true'
    spec:
      controllerName: konghq.com/kic-gateway-controller
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: Gateway
    metadata:
      name: kong
    spec:
      gatewayClassName: kong
      listeners:
      - name: proxy
        port: 80
        protocol: HTTP
        allowedRoutes:
          namespaces:
            from: All
    " | kubectl apply -n kong -f -
    

    {: data-test-prereq="block" }

Prometheus 설치

스크레이프 간격을 설정하고, Grafana 퍼시스턴스를 사용하고, Kong Gateway 대시보드를 설치하려면 values-monitoring.yaml 파일을 만들어요:

prometheus:
  prometheusSpec:
    scrapeInterval: 10s
    evaluationInterval: 30s
grafana:
  persistence:
    enabled: true  # enable persistence using Persistent Volumes
  dashboardProviders:
    dashboardproviders.yaml:
      apiVersion: 1
      providers:
      - name: 'default' # Configure a dashboard provider file to
        orgId: 1        # put Kong dashboard into.
        folder: ''
        type: file
        disableDeletion: false
        editable: true
        options:
          path: /var/lib/grafana/dashboards/default
  dashboards:
    default:
      kong-dash:
        gnetId: 7424  # Install the following Grafana dashboard in the
        revision: 11  # instance: https://grafana.com/dashboards/7424
        datasource: Prometheus
      kic-dash:
        gnetId: 15662
        datasource: Prometheus

Prometheus와 Grafana를 설치하려면, 생성한 values-monitoring.yaml 파일의 경로를 지정해서 다음을 실행해요:

kubectl create namespace monitoring
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install promstack prometheus-community/kube-prometheus-stack --namespace monitoring --version 52.1.0 -f values-monitoring.yaml

기본적으로 kube-prometheus-stack은 릴리스 이름과 같은 release 레이블을 기준으로 ServiceMonitor와 PodMonitor를 선택해요. Kong Ingress Controller를 설치할 때 release 레이블을 설정할 거예요.

Konnect 배포: KIC Control Plane 만들기

Konnect API를 사용해서 새로운 CLUSTER_TYPE_K8S_INGRESS_CONTROLLER Control Plane을 만들어요:

CONTROL_PLANE_DETAILS=$(curl -X POST "https://us.api.konghq.com/v2/control-planes" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "My KIC CP",
       "cluster_type": "CLUSTER_TYPE_K8S_INGRESS_CONTROLLER"
     }'
)

나중에 values.yaml 파일을 작성할 때 id와 telemetry_endpoint가 필요해요. 환경 변수로 저장해두세요:

CONTROL_PLANE_ID=$(echo $CONTROL_PLANE_DETAILS | jq -r .id)
CONTROL_PLANE_TELEMETRY=$(echo $CONTROL_PLANE_DETAILS | jq -r '.config.telemetry_endpoint | sub("https://";"")')

mTLS 인증서 생성

Kong Ingress Controller는 TLS 인증서로 보안이 적용된 연결을 통해 Konnect와 통신해요.

openssl을 사용해서 새 인증서를 생성해요:

openssl req -new -x509 -nodes -newkey rsa:2048 -subj "/CN=kongdp/C=US" -keyout ./tls.key -out ./tls.crt

인증서를 curl로 Konnect API에 전송하려면 한 줄 문자열이어야 해요. awk를 사용해서 인증서 형식을 맞춰요:

export CERT=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' tls.crt);

다음으로, 인증서를 Konnect에 업로드해요:

curl -X POST "https://us.api.konghq.com/v2/control-planes/$CONTROL_PLANE_ID/dp-client-certificates" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "cert": "'$CERT'"
     }'

마지막으로, Kong Ingress Controller가 읽을 수 있도록 인증서를 Kubernetes 시크릿에 저장해요:

kubectl create namespace kong -o yaml --dry-run=client | kubectl apply -f -
kubectl create secret tls konnect-client-tls -n kong --cert=./tls.crt --key=./tls.key

Konnect 배포: Kong Ingress Controller 실행 (Konnect에 연결)

  1. Kong Helm 차트를 추가해요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. values.yaml 파일을 만들어요:

    cat <<EOF > values.yaml
    controller:
      ingressController:
        image:
          tag: "3.5"
        env:
          feature_gates: "FillIDs=true"
        konnect:
          license:
            enabled: true
          enabled: true
          controlPlaneID: "$CONTROL_PLANE_ID"
          tlsClientCertSecretName: konnect-client-tls
          apiHostname: "us.kic.api.konghq.com"
    gateway:
      image:
        repository: kong
        tag: "3.9.3"
      env:
        konnect_mode: 'on'
        vitals: "off"
        cluster_mtls: pki
        cluster_telemetry_endpoint: "$CONTROL_PLANE_TELEMETRY:443"
        cluster_telemetry_server_name: "$CONTROL_PLANE_TELEMETRY"
        cluster_cert: /etc/secrets/konnect-client-tls/tls.crt
        cluster_cert_key: /etc/secrets/konnect-client-tls/tls.key
        lua_ssl_trusted_certificate: system
        proxy_access_log: "off"
        dns_stale_ttl: "3600"
      secretVolumes:
         - konnect-client-tls
    EOF
    

    {: data-test-prereq="block" }

  3. Helm을 사용해서 Kong Ingress Controller를 설치해요:

    helm install kong kong/ingress -n kong --create-namespace --set gateway.serviceMonitor.enabled=true --set gateway.serviceMonitor.labels.release=promstack --values ./values.yaml --wait 
    

    {: data-test-prereq="block" }

  4. 이후 명령어에서 사용할 수 있게 $PROXY_IP를 환경 변수로 설정해요:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

온프레미스 배포: Kong Ingress Controller 실행

  1. Kong Helm 차트를 추가해요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. Helm을 사용해서 Kong Ingress Controller를 설치해요:

    helm install kong kong/ingress -n kong --create-namespace --set gateway.serviceMonitor.enabled=true --set gateway.serviceMonitor.labels.release=promstack --wait 
    

    {: data-test-prereq="block" }

  3. 이후 명령어에서 사용할 수 있게 $PROXY_IP를 환경 변수로 설정해요:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

동작 방식

Kong Gateway는 Gateway Service와 Route 메트릭을 자동으로 내보내는 Prometheus 플러그인을 제공해요.

Prometheus 스택은 servicemonitor 리소스에 정의된 레이블과 일치하는 배포에서 메트릭을 스크레이프해요. Kong Ingress Controller Helm 차트는 배포에 자동으로 레이블을 붙이고 servicemonitor 인스턴스를 만들어서 Prometheus 메트릭 스크레이핑을 활성화할 수 있어요.

Prometheus 활성화

Kong Gateway는 기본적으로 Prometheus 메트릭을 노출하지 않아요. 메트릭을 활성화하려면 prometheus 플러그인 인스턴스를 만들어요:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongClusterPlugin
metadata:
  name: prometheus
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
  labels:
    global: 'true'
config:
  status_code_metrics: true
  bandwidth_metrics: true
  upstream_health_metrics: true
  latency_metrics: true
  per_consumer: false
plugin: prometheus
" | kubectl apply -f -

데모 Service 배포

이 how-to는 프로덕션 환경을 시뮬레이션하기 위해 여러 개의 Service를 Kubernetes 클러스터에 배포해요.

Service를 배포하고 라우팅 리소스를 만들어요:

kubectl apply -f https://developer.konghq.com/manifests/kic/multiple-services.yaml -n kong

Gateway API

echo "
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: sample-routes
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  parentRefs:
  - name: kong
    namespace: kong
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: '/billing'
    backendRefs:
    - name: billing
      kind: Service
      port: 80
  - matches:
    - path:
        type: PathPrefix
        value: '/comments'
    backendRefs:
    - name: comments
      kind: Service
      port: 80
  - matches:
    - path:
        type: PathPrefix
        value: '/invoice'
    backendRefs:
    - name: invoice
      kind: Service
      port: 80
" | kubectl apply -f -

{: data-test-step="block" }

Ingress

echo "
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: sample-routes
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  ingressClassName: kong
  rules:
  - http:
      paths:
      - path: '/billing'
        pathType: ImplementationSpecific
        backend:
          service:
            name: billing
            port:
              number: 80
  - http:
      paths:
      - path: '/comments'
        pathType: ImplementationSpecific
        backend:
          service:
            name: comments
            port:
              number: 80
  - http:
      paths:
      - path: '/invoice'
        pathType: ImplementationSpecific
        backend:
          service:
            name: invoice
            port:
              number: 80
" | kubectl apply -f -

트래픽 생성

Service와 Route가 배포되고 나면 가짜 트래픽을 생성할 차례예요. 같은 터미널 창에서 다음 명령어를 실행해요:

while true;
do
  curl $PROXY_IP/billing/status/200
  curl $PROXY_IP/billing/status/501
  curl $PROXY_IP/invoice/status/201
  curl $PROXY_IP/invoice/status/404
  curl $PROXY_IP/comments/status/200
  curl $PROXY_IP/comments/status/200
  sleep 0.01
done

Grafana 접속

Grafana는 시간 경과에 따른 Prometheus 메트릭을 관찰할 때 사용할 수 있는 옵저버빌리티 도구예요. Grafana에 접속하려면 새 터미널 창에서 Service를 port-forward해야 해요:

kubectl -n monitoring port-forward services/prometheus-operated 9090 &
kubectl -n monitoring port-forward services/promstack-grafana 3000:80 &

admin 사용자의 비밀번호도 가져와야 해요.

비밀번호를 확인하고 복사하려면 다음을 실행해요:

kubectl get secret --namespace monitoring promstack-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo

http://localhost:3000으로 이동해서 사용자 이름 admin과 복사해둔 비밀번호를 입력해요.

로그인하면 왼쪽 아래에 Kong (official) 대시보드가 보여요. 이 링크를 클릭하세요.

수집되는 메트릭

Grafana는 Prometheus에서 스크레이프한 다음 메트릭을 보여줄 수 있어요.

여러 Service의 요청 지연 시간

요청 지연 시간

Kong Gateway는 Service가 요청에 응답하는 데 걸리는 시간에 대한 지연 시간 데이터를 수집해요. 이 데이터를 활용하면 지연 시간이 특정 임계값을 초과했을 때 온콜 엔지니어에게 알림을 보낼 수 있어요. 예를 들어, 요청의 95%에 대해 API가 20밀리초 미만의 지연 시간으로 응답한다는 SLA를 갖고 있다고 해볼게요. 다음 쿼리를 기반으로 알림을 보내도록 Prometheus를 설정할 수 있어요:

histogram_quantile(0.95, sum(rate(kong_request_latency_ms_sum{route=~"$route"}[1m])) by (le)) > 20

이 쿼리는 모든 Service의 전체 요청 지연 시간(또는 duration)에 대한 95백분위수를 계산하고, 그 값이 20밀리초를 넘으면 알림을 보내요. 이 쿼리에서 "type" 레이블은 "request"인데, 이는 Kong Gateway와 Service가 더한 지연 시간을 추적해요. Service만 더한 지연 시간을 추적하고 싶다면 이 값을 "upstream"으로 바꾸면 돼요. Prometheus는 매우 유연하고 문서화도 잘 되어 있어서 여기서 알림 설정 방법을 자세히 다루지는 않을게요. 자세한 내용은 Prometheus 문서에서 찾을 수 있어요.

Kong Gateway 프록시 지연 시간

프록시 지연 시간

Kong Gateway는 자체 성능에 대한 메트릭도 수집해요. 다음 쿼리는 앞선 쿼리와 비슷하지만, Kong Gateway가 더한 지연 시간을 파악할 수 있게 해줘요:

histogram_quantile(0.90, sum(rate(kong_kong_latency_ms_bucket[1m])) by (le,service)) > 2

오류율

오류율

추적할 만한 또 다른 중요한 메트릭은 Service가 처리하는 오류와 요청의 비율이에요. kong_http_status 시계열은 각 Service의 HTTP 상태 코드 메트릭을 수집해요.

이 메트릭을 활용하면 각 Service의 오류율을 추적할 수 있어요:

sum(rate(kong_http_requests_total{code=~"5[0-9]{2}"}[1m])) by (service)

임의의 기간 동안 발생한 요청 중 오류가 차지하는 비율도 계산할 수 있어요. 그 결과를 도출하는 쿼리를 직접 만들어 보세요.

모든 HTTP 상태 코드가 인덱싱되기 때문에, 이 데이터를 활용하면 일반적인 트래픽 패턴을 파악하고 문제를 찾아낼 수 있어요. 예를 들어, 404 응답 코드가 갑자기 급증한다면 최근 배포에서 제거된 엔드포인트를 클라이언트 코드가 요청하고 있다는 신호일 수 있어요.

요청 비율과 대역폭

요청 비율

kong_http_status 시계열을 사용하면 각 Service별로, 또는 Kubernetes 클러스터 전체의 총 요청 비율을 도출할 수 있어요.

대역폭

Kong Gateway가 추적하는 또 다른 메트릭은 소비되는 네트워크 대역폭(kong_bandwidth)의 양이에요. 이를 통해 요청/응답 크기가 인프라의 다른 동작과 어떤 상관관계가 있는지 가늠할 수 있어요.

이제 Service를 전혀 수정하지 않고도 Kubernetes 클러스터 내에서 실행 중인 Service의 메트릭을 확보했고, 애플리케이션을 훨씬 더 잘 파악할 수 있게 됐어요. Alertmanager나 Grafana를 사용해 관찰된 메트릭과 여러분의 SLO를 기반으로 알림을 설정할 수 있어요.

정리

클러스터에서 KIC 제거하기

helm uninstall kong -n kong

FAQ

  • Prometheus 플러그인이 활성화된 Data Plane 노드가 여러 개 있을 때, 메트릭 데이터는 단일 노드의 상태를 반영하나요, 아니면 모든 노드를 집계한 상태를 반영하나요? 메트릭 데이터는 노드별(각 Data Plane)로, 서브시스템별(HTTP 또는 TCP)로 보고돼요.

관련 리소스

더 알아보기 (Learn more)