Search code examples
kubernetesprometheusgrafana

Calculate CPU usage of a pod in a namespace using Prometheus


How to get the CPU usage of a pod in a namespace ? My initial dashboard on Grafana setup looks like this - enter image description here

I'm trying to come up with a query, that gives me the CPU usage of a selected pod of selected namespace in selected cluster. Managed to come up with below one, but it returns "No data".

sum(node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate{pod="$pod", namespace="$namespace"})

Where am I going wrong ?


Solution

  • If you want to calculate the workload CPU utilization per pod, in terms of usage seconds of CPU, you can use this PromQL query:

    sum(rate(container_cpu_usage_seconds_total{namespace="$namespace",
      pod_name=~"$podName",container_name!=""}[1m])) by (pod_name)
    

    where:

    • container_cpu_usage_seconds_total() which gives you how long the CPU has been occupied
    • rate() calculates the per-second average rate of increase of the time series in the range vector
    • [1m] reads the values at the defined interval of 1 minute
    • sum() by (pod_name) adds all values which contain the same pod names, necessary in case of multiple containers in the same pod
    • namespace="$namespace",pod_name=~"$podName",container_name!="" applies the condition to get the pods to consider and filter the rest

    If you want to calculate the workload memory utilization per pod, you can use this query:

    sum(container_memory_working_set_bytes{namespace="$namespace",
      pod_name=~"$podName", container_name!=""}) by (pod_name)