如何使用普罗米修斯作为监控来计算容器在kubernetes中的cpu使用情况?

How to calculate containers' cpu usage in kubernetes with prometheus as monitoring?

我想计算 kubernetes 集群中所有 pods 的 cpu 使用情况。我发现 prometheus 中的两个指标可能有用:

container_cpu_usage_seconds_total: Cumulative cpu time consumed per cpu in seconds.
process_cpu_seconds_total: Total user and system CPU time spent in seconds.

Cpu Usage of all pods = increment per second of sum(container_cpu_usage_seconds_total{id="/"})/increment per second of sum(process_cpu_seconds_total)

但是,我发现每秒的增量container_cpu_usage{id="/"}大于sum(process_cpu_seconds_total)的增量。所以使用量可能大于1...

我用它来获取 CPU 集群级别的使用情况:

sum (rate (container_cpu_usage_seconds_total{id="/"}[1m])) / sum (machine_cpu_cores) * 100

我还跟踪每个 pod 的 CPU 使用情况。

sum (rate (container_cpu_usage_seconds_total{image!=""}[1m])) by (pod_name)

我在 GitHub 上有一个完整的 kubernetes-prometheus 解决方案,也许可以帮助您了解更多指标:https://github.com/camilb/prometheus-kubernetes

您也可以使用以下查询:

avg (rate (container_cpu_usage_seconds_total{id="/"}[1m]))

我创建了自己的 prometheus 导出器 (https://github.com/google-cloud-tools/kube-eagle),主要是为了更好地了解每个节点的资源利用率。但它也提供了一种更直观的方式来监控您的 CPU 和 RAM 资源。获取集群范围 CPU 使用情况的查询如下所示:

sum(eagle_pod_container_resource_usage_cpu_cores)

但您也可以通过命名空间、节点或节点池轻松获得 CPU 用法。

我更喜欢根据 doc

使用此指标
sum(rate(container_cpu_usage_seconds_total{name!~".*prometheus.*", image!="", container_name!="POD"}[5m])) by (pod_name, container_name) /
sum(container_spec_cpu_quota{name!~".*prometheus.*", image!="", container_name!="POD"}/container_spec_cpu_period{name!~".*prometheus.*", image!="", container_name!="POD"}) by (pod_name, container_name)

以下查询 returns per-container 最近 5 分钟内使用的 CPU 平均数:

rate(container_cpu_usage_seconds_total{container!~"POD|"}[5m])

方括号中的lookbehind window(上例中的5m)可以改成需要的值。查看可能的持续时间值 here.

container!~"POD|" 过滤器删除与 cgroups 层次结构相关的指标(参见 this answer for more details) and metrics for e.g. pause containers (see )。

由于每个 pod 可以包含多个容器,因此可以使用以下查询返回 per-pod 最近 5 分钟内使用的 CPU 平均数:

sum(
  rate(container_cpu_usage_seconds_total{container!~"POD|"}[5m])
) by (namespace,pod)