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

Prometheus로 워크로드 오토스케일링

원문 보기 위키 갱신

Prometheus로 워크로드 오토스케일링 (Autoscale workloads with Prometheus)

이 문서는 Prometheus 메트릭을 기반으로 Kong Gateway 워크로드를 자동으로 스케일링하는 방법을 안내해요

출처: 문서

본문

TL;DR

Prometheus 메트릭을 사용해서 Kong Gateway 워크로드는 어떻게 오토스케일할 수 있을까요? Service에서 지연 시간 메트릭을 노출하도록 DataPlaneMetricsExtension을 배포하고, 그다음 해당 메트릭을 데이터 플레인과 연결하도록 Kong Operator를 설정해요. 이렇게 하면 Prometheus나 KEDA 같은 외부 도구가 스케일링 결정을 트리거할 수 있어요.

사전 준비

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/gateway-operator
    ---
    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" }

Kong Operator 실행 (Enterprise 라이선스 필요)

  1. Kong Helm 차트를 추가하세요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. Helm으로 Kong Operator를 설치하세요:

    Konnect 배포

    helm upgrade --install kong-operator kong/kong-operator -n kong-system \
      --create-namespace \
      --set image.tag=2.3 \
      --set env.ENABLE_CONTROLLER_KONNECT=true
    

    온프레미스 배포

    helm upgrade --install kong-operator kong/kong-operator -n kong-system \
      --create-namespace \
      --set image.tag=2.3 \
    

    cert-manager가 어드미션 및 컨버전 웹훅 인증서를 발급하고 갱신하길 원한다면, 클러스터에 cert-manager를 설치하고, 다음 단계에서 설치할 때 아래 인자를 전달해서 cert-manager 통합을 활성화하세요:

    --set global.webhooks.options.certManager.enabled=true
    

    이걸 활성화하지 않으면 차트가 자체 서명 인증서를 자동으로 생성해서 주입해요. 이 인증서들의 라이프사이클을 관리하려면 cert-manager를 활성화하는 걸 추천해요. Kong Operator는 컨트롤 플레인과 데이터 플레인 간 mTLS 통신용 인증서에 서명할 인증 기관이 필요해요. 이건 Helm 차트가 자동으로 처리해 줘요. 커스텀 CA 인증서를 제공해야 한다면, Helm 차트의 values.yaml에 있는 certificateAuthority 섹션을 참고해서 자체 CA 인증서를 만들고 참조하는 방법을 확인하세요.

온프레미스 배포

KongLicense를 적용하세요. 이때 라이선스가 ./license.json에 준비되어 있다고 가정해요.

echo "
apiVersion: configuration.konghq.com/v1alpha1
kind: KongLicense
metadata:
 name: kong-license
rawLicenseString: '$(cat ./license.json)'
" | kubectl apply -f -

필요한 Kubernetes 리소스

이 how-to를 진행하려면 클러스터에서 몇 가지 Kubernetes 서비스를 사용할 수 있어야 해요. 이 how-to에서 생성하는 리소스들이 이 서비스들을 사용하게 돼요.

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

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

이 how-to에는 사전 구성된 라우트 1개도 필요해요:

Gateway API

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

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

Ingress

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

서비스 파드가 준비될 때까지 기다리세요:

kubectl wait --for=condition=Ready pod --all -n kong --timeout=300s

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

워크로드 오토스케일링

이 튜토리얼은 Service 지연 시간을 기준으로 워크로드를 오토스케일하는 방법을 보여줘요. 사전 준비에서 만든 command 서비스 덕분에 응답에 인위적인 지연을 주입해서 오토스케일링을 트리거할 수 있어요.

DataPlaneMetricsExtension 생성

DataPlaneMetricsExtension을 사용하면 Kong Operator가 Service 지연 시간을 모니터링하고 /metrics 엔드포인트로 노출할 수 있어요.

  1. command 서비스를 가리키는 DataPlaneMetricsExtension을 생성하세요:

    echo '
    kind: DataPlaneMetricsExtension
    apiVersion: gateway-operator.konghq.com/v1alpha1
    metadata:
      name: kong
      namespace: kong
    spec:
      serviceSelector:
        matchNames:
        - name: command
      config:
        latency: true
    ' | kubectl apply -f -
    
  2. 이걸 사용하는 GatewayConfiguration을 생성하세요:

    echo '
    kind: GatewayConfiguration
    apiVersion: gateway-operator.konghq.com/v2beta1
    metadata:
      name: kong
      namespace: kong
    spec:
      extensions:
      - kind: DataPlaneMetricsExtension
        group: gateway-operator.konghq.com
        name: kong
    ' | kubectl apply -f -
    
  3. 이 설정을 사용하도록 GatewayClass를 패치하세요:

    kubectl patch -n kong --type=json gatewayclass kong -p='[
        {
            "op":"add",
            "path":"/spec/parametersRef",
            "value":{
                    "group": "gateway-operator.konghq.com",
                    "kind": "GatewayConfiguration",
                    "name": "kong",
                    "namespace": "kong",
            }
        }
    ]'
    

Prometheus 설치

참고: 현재 사용 중인 Prometheus 설정을 재사용하고 이 단계를 건너뛸 수도 있어요. 다만 Kong Operator의 메트릭을 스크랩할 수 있어야 하고(예: ServiceMonitor를 통해), 배포된 네임스페이스를 메모해 두세요.

  1. prometheus-community Helm 차트를 추가하세요:

    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
    helm repo update
    
  2. kube-prometheus-stack Helm 차트로 Prometheus를 설치하세요:

    helm upgrade --install --create-namespace -n prometheus prometheus prometheus-community/kube-prometheus-stack
    

Kong Operator를 스크랩할 ServiceMonitor 생성

Prometheus가 Kong Operator의 /metrics 엔드포인트를 스크랩하도록 하려면 ServiceMonitor를 생성해야 해요:

echo '
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  labels:
    release: prometheus
  name: gateway-operator
  namespace: kong-system
spec:
  endpoints:
  - port: https
    scheme: http
    path: /metrics
    bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
  selector:
    matchLabels:
      control-plane: controller-manager ' | kubectl apply -f -

위 매니페스트를 적용한 후에는 Kong Operator가 노출하는 메트릭 중 하나를 확인해서 스크랩 설정이 제대로 적용됐는지 검증할 수 있어요.

Prometheus UI에 접속하려면 port-forward를 생성하고 http://localhost:9090으로 접속하세요:

kubectl port-forward service/prometheus-kube-prometheus-prometheus 9090:9090 -n prometheus

Prometheus UI로 이동해서 아래 쿼리를 날리면 확인할 수 있어요:

up{service=~"kgo-gateway-operator-metrics-service"}

Prometheus 메트릭이 나타나기까지 최대 2분이 걸릴 수 있어요.

prometheus-adapter 설치

prometheus-adapter 패키지는 Prometheus 메트릭을 Kubernetes에서 사용할 수 있게 만들어 줘요.

prometheus-adapter를 배포하려면 Kubernetes가 소비할 수 있도록 어떤 시계열을 노출할지 먼저 정해야 해요.

참고: Kong Operator는 prometheus-adapter에서 사용할 수 있도록 특정 메트릭을 보강해요. 전체 목록은 개요를 참고하세요.

prometheus-adapter Helm 차트를 배포하려면 values.yaml 파일을 생성하세요. 이 설정은 kong_upstream_latency_ms_60s_average 메트릭을 계산하는데, 이 메트릭은 업스트림 응답 지연 시간의 60초 이동 평균을 노출해요:

echo $'
prometheus:
  # Update this value if Prometheus is installed in a different namespace
  url: http://prometheus-kube-prometheus-prometheus.prometheus.svc

rules:
  default: false
  custom:
  - seriesQuery: \'{__name__=~"^kong_upstream_latency_ms_(sum|count)",kubernetes_namespace!="",kubernetes_name!="",kubernetes_kind!=""}\'
    resources:
      overrides:
        exported_namespace:
          resource: "namespace"
        exported_service:
          resource: "service"
    name:
      as: "kong_upstream_latency_ms_60s_average"
    metricsQuery: |
      sum by (exported_service) (rate(kong_upstream_latency_ms_sum{<<.LabelMatchers>>}[60s:10s]))
        /
      sum by (exported_service) (rate(kong_upstream_latency_ms_count{<<.LabelMatchers>>}[60s:10s]))
' > values.yaml

Helm으로 prometheus-adapter를 설치하세요:

helm upgrade --install --create-namespace -n prometheus --values values.yaml prometheus-adapter prometheus-community/prometheus-adapter

트래픽 보내기

오토스케일링을 트리거하려면 새 터미널 창에서 다음 명령어를 실행하세요. 그러면 기반이 되는 deployment가 각 요청마다 100ms 동안 sleep하게 돼서 평균 응답 시간이 그 값으로 늘어나요.

while curl -k "http://$(kubectl get -n kong gateway kong -o custom-columns='name:.status.addresses[0].value' --no-headers)/command/shell?cmd=sleep%200.1" ; do sleep 1; done

다음 단계로 넘어가는 동안 이 명령어는 계속 실행 상태로 두세요.

Kubernetes에서 메트릭이 노출되는지 확인

모든 설정이 끝나면 prometheus-adapter에서 설정한 메트릭이 Kubernetes Custom Metrics API를 통해 노출되는 걸 확인할 수 있어야 해요:

kubectl get --raw '/apis/custom.metrics.k8s.io/v1beta1/namespaces/kong/services/command/kong_upstream_latency_ms_60s_average' | jq

참고: prometheus-adapter가 커스텀 메트릭을 채우는 데 최대 2분이 걸릴 수 있어요

그러면 다음과 같은 결과가 나와요:

{
  "kind": "MetricValueList",
  "apiVersion": "custom.metrics.k8s.io/v1beta1",
  "metadata": {},
  "items": [
    {
      "describedObject": {
        "kind": "Service",
        "namespace": "kong",
        "name": "command",
        "apiVersion": "/v1"
      },
      "metricName": "kong_upstream_latency_ms_60s_average",
      "timestamp": "2024-03-06T13:11:12Z",
      "value": "102312m",
      "selector": null
    }
  ]
}

{:.no-copy-code}

참고: 102312m은 Kubernetes에서 숫자를 정수로 표현하는 방식이에요. value는 마이크로초 단위의 지연 시간을 나타내며, 대략 102밀리초(ms)에 해당해요.

HorizontalPodAutoscaler에서 노출된 메트릭 사용하기

prometheus-adapter에 설정된 메트릭이 Kubernetes의 Custom Metrics API를 통해 제공되면, HorizontalPodAutoscaler에서 이 메트릭을 사용해 워크로드, 정확히는 command Deployment를 오토스케일할 수 있어요.

다음 매니페스트를 사용하면 돼요. 이 매니페스트는 command Deployment를 1개에서 10개 레플리카 사이로 스케일하면서, 지난 60초 동안의 평균 지연 시간을 40ms로 유지하려고 해요.

echo '
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: command
  namespace: kong
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: command
  minReplicas: 1
  maxReplicas: 10
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 1
      policies:
      - type: Percent
        value: 100
        periodSeconds: 10
    scaleUp:
      stabilizationWindowSeconds: 1
      policies:
      - type: Percent
        value: 100
        periodSeconds: 2
      - type: Pods
        value: 4
        periodSeconds: 2
      selectPolicy: Max
  metrics:
  - type: Object
    object:
      metric:
        name: "kong_upstream_latency_ms_60s_average"
      describedObject:
        apiVersion: v1
        kind: Service
        name: command
      target:
        type: Value
        value: "40" ' | kubectl apply -f -

Kubernetes SuccessfulRescale 이벤트 관찰하기

다음 kubectl 커맨드로 SuccessfulRescale 이벤트를 지켜볼 수 있어요:

kubectl get events -n kong --field-selector involvedObject.name=command --field-selector involvedObject.kind=HorizontalPodAutoscaler -w

모든 게 잘 진행됐다면 SuccessfulRescale 이벤트를 볼 수 있어요:

12m          Normal   SuccessfulRescale   horizontalpodautoscaler/command   New size: 2; reason: Service metric kong_upstream_latency_ms_60s_average above target
12m          Normal   SuccessfulRescale   horizontalpodautoscaler/command   New size: 4; reason: Service metric kong_upstream_latency_ms_60s_average above target
12m          Normal   SuccessfulRescale   horizontalpodautoscaler/command   New size: 8; reason: Service metric kong_upstream_latency_ms_60s_average above target
12m          Normal   SuccessfulRescale   horizontalpodautoscaler/command   New size: 10; reason: Service metric kong_upstream_latency_ms_60s_average above target

{:.no-copy-code}

그다음 지연 시간이 떨어지면(curl 커맨드로 트래픽 전송을 멈췄을 때) 워크로드가 스케일 다운되는 SuccessfulRescale 이벤트를 관찰할 수 있어요:

4s          Normal   SuccessfulRescale   horizontalpodautoscaler/command   New size: 1; reason: All metrics below target

{:.no-copy-code}

더 알아보기 (Learn more)

  • Konnect 계정이 아직 없다면 온보딩 마법사로 빠르게 가입을 시작할 수 있어요 — onboarding wizard
  • 튜토리얼 진행에 필요한 Konnect 개인 액세스 토큰(PAT)을 발급받는 페이지예요 — Konnect PAT page
  • 데이터 플레인 오토스케일링과 메트릭 지원(enrichment)에 대한 전체 개요를 담은 참고 문서예요 — overview