GKE에서 Prometheus를 사용하여 애플리케이션 관측 가능성


이 튜토리얼에서는 오픈소스 Prometheus를 사용하여 Google Kubernetes Engine(GKE)에 배포된 애플리케이션 마이크로서비스에 활성 프로브를 설정하는 방법을 보여줍니다.

이 가이드에서는 오픈소스 Prometheus를 사용합니다. 하지만 각 GKE Autopilot 클러스터는 Prometheus 측정항목을 위한 Google Cloud의 완전 관리형 멀티 클라우드 프로젝트 솔루션인 Managed Service for Prometheus를 자동으로 배포합니다. Managed Service for Prometheus를 이용하면 수동으로 대규모 Prometheus 관리 및 운영을 수행할 필요 없이 Prometheus를 사용하여 워크로드를 모니터링하고 알림을 표시할 수 있습니다.

Grafana와 같은 오픈소스 도구를 사용하여 Prometheus에서 수집한 측정항목을 시각화할 수도 있습니다.

목표

  • 클러스터를 만듭니다.
  • Prometheus를 배포합니다.
  • 샘플 애플리케이션인 Bank of Anthos를 배포합니다.
  • Prometheus 활성 프로브를 구성합니다.
  • Prometheus 알림을 구성합니다.
  • Slack 채널에서 알림을 받도록 Alertmanager를 구성합니다.
  • Prometheus 테스트를 위해 중단을 시뮬레이션합니다.

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

이 문서에 설명된 태스크를 완료했으면 만든 리소스를 삭제하여 청구가 계속되는 것을 방지할 수 있습니다. 자세한 내용은 삭제를 참조하세요.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 프로젝트 만들기를 클릭하여 새 Google Cloud 프로젝트 만들기를 시작합니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. GKE API 사용 설정

    API 사용 설정

  5. Google Cloud Console의 프로젝트 선택기 페이지에서 프로젝트 만들기를 클릭하여 새 Google Cloud 프로젝트 만들기를 시작합니다.

    프로젝트 선택기로 이동

  6. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  7. GKE API 사용 설정

    API 사용 설정

  8. Helm API 를 설치합니다.

환경 준비

이 튜토리얼에서는 Cloud Shell을 사용하여 Google Cloud에서 호스팅되는 리소스를 관리합니다.

  1. 기본 환경 변수를 설정합니다.

    gcloud config set project PROJECT_ID
    gcloud config set compute/region COMPUTE_REGION
    

    다음을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID
    • PROJECT_ID: 클러스터의 Compute Engine 리전. 이 튜토리얼에서 리전은 us-central1입니다. 일반적으로 자신에게 가까운 리전이 필요합니다.
  2. 이 튜토리얼에 사용된 샘플 저장소를 클론합니다.

    git clone https://github.com/GoogleCloudPlatform/bank-of-anthos.git
    cd bank-of-anthos/
    
  3. 클러스터 만들기:

    gcloud container clusters create-auto CLUSTER_NAME \
        --release-channel=CHANNEL_NAME \
        --region=COMPUTE_REGION
    

    다음을 바꿉니다.

    • CLUSTER_NAME: 새 클러스터의 이름
    • CHANNEL_NAME: 출시 채널의 이름

Prometheus 배포

샘플 Helm 차트를 사용하여 PostgreSQL을 설치하세요.

helm repo add bitnami https://charts.bitnami.com/bitnami
helm install tutorial bitnami/kube-prometheus \
    --version 8.2.2 \
    --values extras/prometheus/oss/values.yaml \
    --wait

이 명령어는 다음 구성요소를 사용하여 Prometheus를 설치합니다.

  • Prometheus 연산자: 오픈소스 Prometheus를 배포하고 구성하는 데 널리 사용되는 방법입니다.
  • Alertmanager: Prometheus 서버에서 전송된 알림을 처리하고 Slack과 같은 애플리케이션으로 라우팅합니다.
  • 블랙박스 내보내기: Prometheus가 HTTP, HTTPS, DNS, TCP, ICMP, gRPC를 사용하여 엔드포인트를 조사할 수 있습니다.

Bank of Anthos 배포

Bank of Anthos 샘플 애플리케이션을 배포하세요.

kubectl apply -f extras/jwt/jwt-secret.yaml
kubectl apply -f kubernetes-manifests

Slack 알림

Slack 알림을 설정하려면 Slack 애플리케이션을 만들고, 이 애플리케이션에 대한 수신 웹훅을 활성화한 다음 Slack 작업공간에 애플리케이션을 설치해야 합니다.

Slack 애플리케이션 만들기

  1. 이메일로 등록하거나 작업공간 관리자가 보낸 초대를 사용하여 Slack 작업공간에 가입합니다.

  2. 작업공간 이름과 Slack 계정 사용자 인증 정보를 사용하여 Slack에 로그인합니다.

  3. 새 Slack 앱을 만듭니다.

    1. Create an app(앱 만들기) 대화상자에서 From scratch(처음부터)를 클릭합니다.
    2. App Name(앱 이름)을 지정하고 Slack 작업공간을 선택합니다.
    3. Create App을 클릭합니다.
    4. Add features and functionality(특징 및 기능 추가)에서 Incoming Webhooks(수신 웹훅)를 클릭합니다.
    5. Activate Incoming Webhooks(수신 웹훅 활성화) 전환 버튼을 클릭합니다.
    6. Webhook URLs for Your Workspace(작업공간의 웹훅 URL) 섹션에서 Add New Webhook to Workspace(작업공간에 새 웹훅 추가)를 클릭합니다.
    7. 승인 페이지가 열리면 알림을 수신할 채널을 선택합니다.
    8. 허용을 클릭합니다.
    9. Slack 애플리케이션의 웹훅이 Webhook URLs for Your Workspace(작업공간의 웹훅 URL) 섹션에 표시됩니다. 나중을 위해 이 URL을 저장합니다.

Alertmanager 구성

웹훅 URL을 저장할 Kubernetes 보안 비밀을 만듭니다.

kubectl create secret generic alertmanager-slack-webhook --from-literal webhookURL=SLACK_WEBHOOK_URL
kubectl apply -f extras/prometheus/oss/alertmanagerconfig.yaml

SLACK_WEBHOOK_URL을 이전 섹션의 웹훅 URL로 바꿉니다.

Prometheus 구성

  1. 다음 매니페스트를 검토합니다.

    # Copyright 2023 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: frontend-probe
    spec:
      jobName: frontend
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - frontend:80
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: userservice-probe
    spec:
      jobName: userservice
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - userservice:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: balancereader-probe
    spec:
      jobName: balancereader
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - balancereader:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: contacts-probe
    spec:
      jobName: contacts
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - contacts:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: ledgerwriter-probe
    spec:
      jobName: ledgerwriter
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - ledgerwriter:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: transactionhistory-probe
    spec:
      jobName: transactionhistory
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - transactionhistory:8080/ready
    

    이 매니페스트는 Prometheus 활성 프로브를 설명하고 다음 필드를 포함합니다.

    • spec.jobName: 스크래핑된 측정항목에 할당된 작업 이름입니다.
    • spec.prober.url: 블랙박스 내보내기의 서비스 URL입니다. 여기에는 Helm 차트에 정의된 블랙박스 내보내기의 기본 포트가 포함됩니다.
    • spec.prober.path: 측정항목 수집 경로입니다.
    • spec.targets.staticConfig.labels: 대상에서 스크래핑한 모든 측정항목에 할당된 라벨입니다.
    • spec.targets.staticConfig.static: 프로브할 호스트 목록입니다.
  2. 매니페스트를 클러스터에 적용합니다.

    kubectl apply -f extras/prometheus/oss/probes.yaml
    
  3. 다음 매니페스트를 검토합니다.

    # Copyright 2023 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: PrometheusRule
    metadata:
      name: uptime-rule
    spec:
      groups:
      - name: Micro services uptime
        interval: 60s
        rules:
        - alert: BalancereaderUnavaiable
          expr: probe_success{app="bank-of-anthos",job="balancereader"} == 0
          for: 1m
          annotations:
            summary: Balance Reader Service is unavailable
            description: Check Balance Reader pods and it's logs
          labels:
            severity: 'critical'
        - alert: ContactsUnavaiable
          expr: probe_success{app="bank-of-anthos",job="contacts"} == 0
          for: 1m
          annotations:
            summary: Contacs Service is unavailable
            description: Check Contacs pods and it's logs
          labels:
            severity: 'warning'
        - alert: FrontendUnavaiable
          expr: probe_success{app="bank-of-anthos",job="frontend"} == 0
          for: 1m
          annotations:
            summary: Frontend Service is unavailable
            description: Check Frontend pods and it's logs
          labels:
            severity: 'critical'
        - alert: LedgerwriterUnavaiable
          expr: probe_success{app="bank-of-anthos",job="ledgerwriter"} == 0
          for: 1m
          annotations:
            summary: Ledger Writer Service is unavailable
            description: Check Ledger Writer pods and it's logs
          labels:
            severity: 'critical'
        - alert: TransactionhistoryUnavaiable
          expr: probe_success{app="bank-of-anthos",job="transactionhistory"} == 0
          for: 1m
          annotations:
            summary: Transaction History Service is unavailable
            description: Check Transaction History pods and it's logs
          labels:
            severity: 'critical'
        - alert: UserserviceUnavaiable
          expr: probe_success{app="bank-of-anthos",job="userservice"} == 0
          for: 1m
          annotations:
            summary: User Service is unavailable
            description: Check User Service pods and it's logs
          labels:
            severity: 'critical'
    

    이 매니페스트는 PrometheusRule을 설명하며 다음 필드를 포함합니다.

    • spec.groups.[*].name: 규칙 그룹의 이름입니다.
    • spec.groups.[*].interval: 그룹의 규칙이 평가되는 빈도입니다.
    • spec.groups.[*].rules[*].alert: 알림의 이름입니다.
    • spec.groups.[*].rules[*].expr: 평가할 PromQL 표현식입니다.
    • spec.groups.[*].rules[*].for: 알림이 실행된 것으로 간주되기 전에 반환해야 하는 시간입니다.
    • spec.groups.[*].rules[*].annotations: 각 알림에 추가할 주석 목록입니다. 이는 알림 규칙에만 유효합니다.
    • spec.groups.[*].rules[*].labels: 추가하거나 덮어쓸 라벨입니다.
  4. 매니페스트를 클러스터에 적용합니다.

    kubectl apply -f extras/prometheus/oss/rules.yaml
    

중단 시뮬레이션

  1. contacts 배포를 0으로 확장하여 중단을 시뮬레이션하세요.

    kubectl scale deployment contacts --replicas 0
    

    Slack 작업공간 채널에 알림 메시지가 표시됩니다. GKE가 배포를 확장하는 데 최대 5분이 걸릴 수 있습니다.

  2. contacts 배포를 복원합니다.

    kubectl scale deployment contacts --replicas 1
    

    Slack 작업공간 채널에 알림 해결 알림 메시지가 표시됩니다. GKE가 배포를 확장하는 데 최대 5분이 걸릴 수 있습니다.

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

    Google Cloud 프로젝트를 삭제합니다.

    gcloud projects delete PROJECT_ID

개별 리소스 삭제

  1. Kubernetes 리소스를 삭제합니다.

    kubectl delete -f kubernetes-manifests
    
  2. Prometheus를 제거합니다.

    helm uninstall tutorial
    
  3. GKE 클러스터를 삭제합니다.

    gcloud container clusters delete CLUSTER_NAME --quiet
    

다음 단계