Prometheus 监控 K8s 集群中 Pod 资源使用率的指标选择与告警配置

一、核心指标选择
  1. CPU 使用率指标

    • 核心指标:container_cpu_usage_seconds_total
    • 计算公式:
      $$ \text{CPU 使用率} = \frac{\text{rate}( \texttt{container_cpu_usage_seconds_total}{ \texttt{container!=""} }[1m] )}{\text{CPU 请求量}} \times 100% $$
    • 说明:
      • 排除 container=""(系统容器)
      • rate() 计算 1 分钟内平均 CPU 使用量(单位:核)
      • 需关联容器的 CPU 请求量(通过 kube_pod_container_resource_requests 获取)
  2. 内存使用率指标

    • 核心指标:container_memory_working_set_bytes
    • 计算公式:
      $$ \text{内存使用率} = \frac{\texttt{container_memory_working_set_bytes}{ \texttt{container!=""} }}{\text{内存请求量}} \times 100% $$
    • 说明:
      • 使用 working_set 反映实际占用内存
      • 需关联容器的内存请求量(通过 kube_pod_container_resource_requests 获取)

二、告警规则配置(YAML 示例)
groups:
- name: pod-resource-alerts
  rules:
  # CPU 使用率 > 85% 持续 5 分钟
  - alert: HighPodCPUUsage
    expr: |
      ( 
        rate(container_cpu_usage_seconds_total{container!=""}[5m]) 
        / 
        kube_pod_container_resource_requests{resource="cpu"} 
      ) * 100 > 85
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "Pod CPU 使用率过高 ({{ $labels.pod }})"
      description: "Pod {{ $labels.pod }} CPU 使用率 {{ $value }}% > 85%"

  # 内存使用率 > 90% 持续 5 分钟
  - alert: HighPodMemoryUsage
    expr: |
      ( 
        container_memory_working_set_bytes{container!=""} 
        / 
        kube_pod_container_resource_requests{resource="memory"} 
      ) * 100 > 90
    for: 5m
    labels:
      severity: critical
    annotations:
      summary: "Pod 内存使用率过高 ({{ $labels.pod }})"
      description: "Pod {{ $labels.pod }} 内存使用率 {{ $value }}% > 90%"


三、关键配置说明
  1. 指标关联

    • 依赖组件:
      • cAdvisor(自动暴露容器指标)
      • kube-state-metrics(提供资源请求量指标 kube_pod_container_resource_requests
    • 验证指标:
      {__name__=~"container_cpu_usage_seconds_total|container_memory_working_set_bytes|kube_pod_container_resource_requests"}
      

  2. 告警优化建议

    • 排除特定命名空间(如 kube-system):
      expr 中添加 namespace!="kube-system"
    • 动态阈值
      对关键服务设置更低阈值(如 >75%)
    • 自动恢复检测
      添加恢复通知规则(需配合 Alertmanager)
  3. 部署流程

    # 1. 将告警规则保存为 pod-alerts.yaml
    # 2. 挂载到 Prometheus 配置
    prometheus:
      rule_files:
        - /etc/prometheus/rules/pod-alerts.yaml
    # 3. 重启 Prometheus
    kubectl rollout restart statefulset prometheus-k8s -n monitoring
    


四、注意事项
  1. 资源请求量必须配置

    • 若未设置 resources.requests,分母为 0 会导致计算失败
    • 解决方案:添加过滤条件 kube_pod_container_resource_requests > 0
  2. 指标标签对齐

    • 确保 container_cpu_usage_seconds_totalkube_pod_container_resource_requests 的标签一致(如 pod/container
    • 不匹配时使用 on(pod, container) 指定关联字段:
      (rate(container_cpu_...}[5m]) / on(pod,container) kube_pod_...)
      

  3. 避免误报

    • 初始启动期豁免:添加 pod_creation_timestamp[1h] 排除新建 Pod
    • 短生命周期 Pod:通过 kube_pod_status_phase{phase="Running"} 过滤非运行状态 Pod

通过上述配置,可实现基于实际资源请求量的动态阈值告警,精准识别资源瓶颈。

更多推荐