Kubernetes 상태 측정항목

이 문서에서는 Google Cloud Managed Service for Prometheus를 사용하여 Kubernetes 상태 측정항목에서 측정항목을 수집할 수 있도록 Google Kubernetes Engine 배포를 구성하는 방법을 설명합니다. 이 문서에서는 다음을 수행하는 방법을 보여줍니다.

  • 측정항목을 보고하도록 Kubernetes 상태 측정항목을 설정합니다.
  • 내보낸 측정항목을 수집하도록 Managed Service for Prometheus의 PodMonitoring 리소스를 구성합니다.
  • 측정항목을 보도록 Cloud Monitoring의 대시보드에 액세스합니다.
  • 측정항목을 모니터링하도록 알림 규칙을 구성합니다.

이 안내는 관리형 컬렉션을 Managed Service for Prometheus와 함께 사용하는 경우에만 적용됩니다. 자체 배포 컬렉션을 사용하는 경우 Kubernetes 상태 측정항목용 소스 저장소에서 설치 정보를 참조하세요.

이 안내는 예시로서 제공되며 대부분의 Kubernetes 환경에서 작동합니다. 제한적인 보안 또는 조직 정책으로 인해 애플리케이션 또는 내보내기 도구를 설치하는 데 문제가 있으면 지원을 위한 오픈소스 문서를 참조하는 것이 좋습니다.

기본 요건

Managed Service for Prometheus 및 관리형 컬렉션을 사용하여 Kubernetes 상태 측정항목에서 측정항목을 수집하려면 배포가 다음 요구사항을 충족해야 합니다.

  • 클러스터가 Google Kubernetes Engine 버전 1.21.4-gke.300 이상을 실행 중이어야 합니다.
  • 관리형 컬렉션이 사용 설정된 상태에서 Managed Service for Prometheus를 실행 중이어야 합니다. 자세한 내용은 관리형 컬렉션 시작하기를 참조하세요.

  • Cloud Monitoring에서 사용할 수 있는 대시보드를 통합에 사용하려면 kube-state-metrics 버전 2.4.2 이상을 사용해야 합니다.

    사용 가능한 대시보드에 대한 자세한 내용은 대시보드 설치를 참조하세요.

관리형 Kube 상태 측정항목

GKE는 이 통합을 구성하는 대신 kube 상태 측정항목의 완전 관리형 배포를 제공합니다. 설치 가능한 패키지는 설정 작업이 적은 독자적으로 선별된 Kubernetes 상태 측정항목을 제공합니다. 자세한 내용은 패키지: Kubernetes 상태 측정항목을 참조하세요.

Kubernetes 상태 측정항목 설치

다음 구성을 사용하여 Kubernetes 상태 측정항목을 설치할 수 있습니다.

# 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
#
#     https://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: apps/v1
kind: StatefulSet
metadata:
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
  namespace: gmp-public
  name: kube-state-metrics
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  serviceName: kube-state-metrics
  template:
    metadata:
      labels:
        app.kubernetes.io/name: kube-state-metrics
        app.kubernetes.io/version: 2.8.2
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/arch
                operator: In
                values:
                - arm64
                - amd64
              - key: kubernetes.io/os
                operator: In
                values:
                - linux
      containers:
      - name: kube-state-metric
        image: k8s.gcr.io/kube-state-metrics/kube-state-metrics:v2.8.2
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        args:
        - --pod=$(POD_NAME)
        - --pod-namespace=$(POD_NAMESPACE)
        - --port=8080
        - --telemetry-port=8081
        ports:
        - name: metrics
          containerPort: 8080
        - name: metrics-self
          containerPort: 8081
        resources:
          requests:
            cpu: 100m
            memory: 190Mi
          limits:
            memory: 250Mi
        securityContext:
          allowPrivilegeEscalation: false
          privileged: false
          capabilities:
            drop:
            - all
          runAsUser: 1000
          runAsGroup: 1000
        livenessProbe:
          httpGet:
            path: /healthz
            port: 8080
          initialDelaySeconds: 5
          timeoutSeconds: 5
        readinessProbe:
          httpGet:
            path: /
            port: 8081
          initialDelaySeconds: 5
          timeoutSeconds: 5
      serviceAccountName: kube-state-metrics
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
  namespace: gmp-public
  name: kube-state-metrics
spec:
  clusterIP: None
  ports:
  - name: metrics
    port: 8080
    targetPort: metrics
  - name: metrics-self
    port: 8081
    targetPort: metrics-self
  selector:
    app.kubernetes.io/name: kube-state-metrics
---
apiVersion: v1
kind: ServiceAccount
metadata:
  namespace: gmp-public
  name: kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: gmp-public:kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: gmp-public:kube-state-metrics
subjects:
- kind: ServiceAccount
  namespace: gmp-public
  name: kube-state-metrics
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: gmp-public:kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
rules:
- apiGroups:
  - ""
  resources:
  - configmaps
  - secrets
  - nodes
  - pods
  - services
  - resourcequotas
  - replicationcontrollers
  - limitranges
  - persistentvolumeclaims
  - persistentvolumes
  - namespaces
  - endpoints
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
- apiGroups:
  - extensions
  resources:
  - daemonsets
  - deployments
  - replicasets
  - ingresses
  verbs:
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - statefulsets
  - daemonsets
  - deployments
  - replicasets
  verbs:
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - statefulsets
  verbs:
  - get
- apiGroups:
  - batch
  resources:
  - cronjobs
  - jobs
  verbs:
  - list
  - watch
- apiGroups:
  - autoscaling
  resources:
  - horizontalpodautoscalers
  verbs:
  - list
  - watch
- apiGroups:
  - authentication.k8s.io
  resources:
  - tokenreviews
  verbs:
  - create
- apiGroups:
  - authorization.k8s.io
  resources:
  - subjectaccessreviews
  verbs:
  - create
- apiGroups:
  - policy
  resources:
  - poddisruptionbudgets
  verbs:
  - list
  - watch
- apiGroups:
  - certificates.k8s.io
  resources:
  - certificatesigningrequests
  verbs:
  - list
  - watch
- apiGroups:
  - storage.k8s.io
  resources:
  - storageclasses
  - volumeattachments
  verbs:
  - list
  - watch
- apiGroups:
  - admissionregistration.k8s.io
  resources:
  - mutatingwebhookconfigurations
  - validatingwebhookconfigurations
  verbs:
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - networkpolicies
  - ingresses
  verbs:
  - list
  - watch
- apiGroups:
  - coordination.k8s.io
  resources:
  - leases
  verbs:
  - list
  - watch
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: kube-state-metrics
  namespace: gmp-public
spec:
  maxReplicas: 10
  minReplicas: 1
  scaleTargetRef:
    apiVersion: apps/v1
    kind: StatefulSet
    name: kube-state-metrics
  metrics:
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 60
  behavior:
    scaleDown:
      policies:
      - type: Pods
        value: 1
        # Under-utilization needs to persist for `periodSeconds` before any action can be taken.
        # Current supported max from https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/horizontal-pod-autoscaler-v2beta2/.
        periodSeconds: 1800
      # Current supported max from https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/horizontal-pod-autoscaler-v2beta2/.
      stabilizationWindowSeconds: 3600
---
apiVersion: monitoring.googleapis.com/v1
kind: ClusterPodMonitoring
metadata:
  name: kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: metrics
    interval: 30s
    metricRelabeling:
    - action: keep
      # Curated subset of metrics to reduce costs while populating default set of sample dashboards at
      # https://github.com/GoogleCloudPlatform/monitoring-dashboard-samples/tree/master/dashboards/kubernetes
      # Change this regex to fit your needs for which objects you want to monitor
      regex: kube_(daemonset|deployment|replicaset|pod|namespace|node|statefulset|persistentvolume|horizontalpodautoscaler|job_created)(_.+)?
      sourceLabels: [__name__]
  targetLabels:
    metadata: [] # explicitly empty so the metric labels are respected
---
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  namespace: gmp-public
  name: kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: metrics-self
    interval: 30s

로컬 파일에서 구성 변경사항을 적용하려면 다음 명령어를 실행합니다.

kubectl apply -f FILE_NAME

Terraform을 사용하여 구성을 관리할 수도 있습니다.

규칙 및 알림 정의

다음 Rules 구성을 사용하여 측정항목에 대한 알림을 정의할 수 있습니다.

# Copyright 2022 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
#
#     https://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.googleapis.com/v1
kind: Rules
metadata:
  namespace: gmp-public
  name: kube-state-metrics-rules
  labels:
    app.kubernetes.io/component: rules
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  groups:
    - name: kube-state-metrics
      interval: 30s
      rules:
      - alert: KubeStateMetricsListErrors
        annotations:
          description: kube-state-metrics is experiencing errors at an elevated rate in list operations. This is likely causing it to not be able to expose metrics about Kubernetes objects correctly or at all.
          summary: kube-state-metrics is experiencing errors in list operations.
        expr: |
          (sum(rate(kube_state_metrics_list_total{job="kube-state-metrics",result="error"}[5m]))
            /
          sum(rate(kube_state_metrics_list_total{job="kube-state-metrics"}[5m])))
          > 0.01
        for: 15m
        labels:
          severity: critical
      - alert: KubeStateMetricsWatchErrors
        annotations:
          description: kube-state-metrics is experiencing errors at an elevated rate in watch operations. This is likely causing it to not be able to expose metrics about Kubernetes objects correctly or at all.
          summary: kube-state-metrics is experiencing errors in watch operations.
        expr: |
          (sum(rate(kube_state_metrics_watch_total{job="kube-state-metrics",result="error"}[5m]))
            /
          sum(rate(kube_state_metrics_watch_total{job="kube-state-metrics"}[5m])))
          > 0.01
        for: 15m
        labels:
          severity: critical
      - alert: KubeStateMetricsShardingMismatch
        annotations:
          description: kube-state-metrics pods are running with different --total-shards configuration, some Kubernetes objects may be exposed multiple times or not exposed at all.
          summary: kube-state-metrics sharding is misconfigured.
        expr: |
          stdvar (kube_state_metrics_total_shards{job="kube-state-metrics"}) != 0
        for: 15m
        labels:
          severity: critical
      - alert: KubeStateMetricsShardsMissing
        annotations:
          description: kube-state-metrics shards are missing, some Kubernetes objects are not being exposed.
          summary: kube-state-metrics shards are missing.
        expr: |
          2^max(kube_state_metrics_total_shards{job="kube-state-metrics"}) - 1
            -
          sum( 2 ^ max by (shard_ordinal) (kube_state_metrics_shard_ordinal{job="kube-state-metrics"}) )
          != 0
        for: 15m
        labels:
          severity: critical

로컬 파일에서 구성 변경사항을 적용하려면 다음 명령어를 실행합니다.

kubectl apply -f FILE_NAME

Terraform을 사용하여 구성을 관리할 수도 있습니다.

클러스터에 규칙을 적용하는 방법에 대한 자세한 내용은 관리형 규칙 평가 및 알림을 참조하세요.

Rules 구성은 kube-state-metrics 저장소에 기여한 규칙과 알림에 맞게 조정되었습니다.

구성 확인

측정항목 탐색기를 사용하여 내보내기 도구를 올바르게 구성했는지 확인할 수 있습니다. Cloud Monitoring이 측정항목을 수집하는 데 1~2분 정도 걸릴 수 있습니다.

측정항목이 수집되었는지 확인하려면 다음을 수행하세요.

  1. Google Cloud 콘솔의 탐색 패널에서 Monitoring을 선택한 후 측정항목 탐색기를 선택합니다.

    측정항목 탐색기로 이동

  2. 쿼리 빌더 창의 툴바에서 이름이  MQL 또는  PromQL인 버튼을 선택합니다.
  3. 언어 전환 버튼에 PromQL이 선택되어 있는지 확인합니다. 언어 전환 버튼은 쿼리 형식을 지정할 수 있는 동일한 툴바에 있습니다.
  4. 다음 쿼리를 입력하고 실행합니다.
    up{job="kube-state-metrics", cluster="CLUSTER_NAME", namespace="gmp-public"}
    

대시보드 설치

Cloud Monitoring은 통합을 위한 샘플 대시보드 라이브러리를 제공합니다. 샘플 라이브러리에는 'Prometheus' 대시보드가 포함되어 있으며, 이를 설치하면 Google Cloud 콘솔에서 데이터를 볼 수 있습니다.

Kubernetes 클러스터 Prometheus 개요 대시보드를 사용하려면 Node Exporter를 설치해야 합니다. Kubernetes 포드 Prometheus 개요 대시보드를 사용하려면 Node ExportercAdvisor/Kubelet을 설치해야 합니다.

샘플 라이브러리에서 대시보드를 설치하려면 다음을 수행합니다.

  1. Google Cloud 콘솔의 탐색 패널에서 Monitoring을 선택한 후 대시보드를 선택합니다.

    대시보드로 이동

  2. 샘플 라이브러리 탭을 선택합니다.
  3. 기타 카테고리를 선택합니다.
  4. (선택사항) 설치하지 않고도 대시보드의 정적 미리보기를 보려면 미리보기를 클릭합니다.
  5. 설치하려는 대시보드를 선택한 다음  가져오기를 클릭합니다.

대시보드 설치에 대한 자세한 내용은 샘플 대시보드 설치를 참조하세요.

문제 해결

측정항목 수집 문제 해결에 대한 자세한 내용은 수집 측 문제 해결에서 내보내기 도구의 수집 관련 문제를 참조하세요.