Containers & Kubernetes monitoring
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Kubernetes is Prometheus’s best-supported deployment target: the kubelet already exposes per-container
resource usage, the API server already knows every node, service, pod and endpoint, and Prometheus
ships a dedicated kubernetes_sd_configs discovery mechanism that reads that API directly. This page
covers the two metric sources you scrape — cAdvisor (resource usage) and kube-state-metrics (cluster
state) — and the discovery roles that find their targets. It assumes the general
relabel_configs mechanics from
Service Discovery & Relabeling; this
page focuses on what is specific to the Kubernetes roles. For container resource limits, logging drivers and
the Docker daemon’s own Prometheus endpoint, see
Resources, Logging and Monitoring. For Kubernetes
observability in general, see
Observability: Logging and Metrics.
The running example is the orders-api service from
Recording & Alerting Rules, now deployed as two
pods in a cluster: the sections below give the RBAC and scrape configuration that find it, the
two metric sources that describe it (cAdvisor and kube-state-metrics), and alert rules that combine them.
kubernetes_sd_configs"] PR -->|"scrape through API server proxy"| KL["kubelet
/metrics/cadvisor"] PR -->|"scrape service endpoints"| KSM["kube-state-metrics"] PR -->|"scrape annotated pods"| APP["orders-api pods
prometheus.io/scrape"] KL --> CM["container_* resource usage"] KSM --> SM["kube_* object state"] APP --> AM["http_requests_total"] CM --> RU["Rules and dashboards"] SM --> RU AM --> RU
cAdvisor: per-container resource metrics
cAdvisor (Container Advisor) is built into the kubelet itself — there is nothing separate to deploy.
Every kubelet exposes it at /metrics/cadvisor, alongside the kubelet’s own /metrics endpoint, and
both are normally scraped through the API server’s proxy rather than reached directly, since the
kubelet’s HTTPS endpoint needs a bearer token and the cluster CA:
scrape_configs:
- job_name: kubernetes-cadvisor
scheme: https
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
authorization:
credentials_file: /var/run/secrets/kubernetes.io/serviceaccount/token
kubernetes_sd_configs:
- role: node
relabel_configs:
- target_label: __address__
replacement: kubernetes.default.svc:443
- source_labels: [__meta_kubernetes_node_name]
regex: (.+)
target_label: __metrics_path__
replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor
# https://prometheus.io/docs/guides/cadvisor/
cAdvisor’s metrics are all resource-usage numbers scoped to a single container: container_cpu_usage_seconds_total,
container_memory_working_set_bytes, container_fs_usage_bytes, container_network_receive_bytes_total,
and so on, each labeled with pod, namespace, container and image. It answers how much a
container is actually consuming, not whether the workload as a whole is healthy — that distinction
matters below. See
Monitoring Docker container metrics using cAdvisor for the
full metric set and a walkthrough of this scrape config.
The same cAdvisor code can be tried on a single Docker host, which is the setup used by the cAdvisor guide:
docker run -d --name cadvisor -p 8080:8080 \
--volume=/:/rootfs:ro --volume=/var/run:/var/run:ro \
--volume=/sys:/sys:ro --volume=/var/lib/docker/:/var/lib/docker:ro \
--privileged gcr.io/cadvisor/cadvisor:v0.49.1
curl -s localhost:8080/metrics | grep -E '^# (HELP|TYPE) container_(cpu_usage_seconds_total|memory_working_set_bytes)'
# HELP container_cpu_usage_seconds_total Cumulative cpu time consumed in seconds.
# TYPE container_cpu_usage_seconds_total counter
# HELP container_memory_working_set_bytes Current working set in bytes.
# TYPE container_memory_working_set_bytes gauge
The types decide how to query them: CPU usage is a counter (take rate() to get cores in use), while
the working set is a gauge (use it directly, and compare it with the container’s limit). On Docker
Desktop, where containers run inside a Linux VM, the standalone cAdvisor reported about 2,200
container_* series labeled only by cgroup id (for example id="/docker/<container id>"), without
the name and image labels a native Linux host provides. Inside Kubernetes the kubelet’s cAdvisor is
combined with pod metadata, which is where the pod, namespace and container labels used below come
from. Series with an empty container label are pod-level cgroups, so queries that mean "a real container"
filter with container!="".
# Per-pod CPU usage over the last 5 minutes, summed across containers.
sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="default"}[5m]))
Memory: working set, not usage
Of the memory metrics, container_memory_working_set_bytes is the one that matches what the kernel’s
OOM killer and the kubelet’s eviction logic look at, so it is the right numerator when comparing against a
limit (the container_memory_usage_bytes metric includes reclaimable page cache and overstates pressure).
Its counterpart for the limit comes from kube-state-metrics (kube_pod_container_resource_limits, used in
the rules at the end of this page) or from container_spec_memory_limit_bytes in cAdvisor itself.
Giving Prometheus access: RBAC
Prometheus can only discover what its service account may read. A scrape configuration that works on a
laptop fails in a cluster with forbidden errors in the server log until a role like this exists (the
nodes/proxy and nodes/metrics entries are what the API-server-proxy cAdvisor scrape needs):
apiVersion: v1
kind: ServiceAccount
metadata:
name: prometheus
namespace: monitoring
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: prometheus
rules:
- apiGroups: [""]
resources: ["nodes", "nodes/metrics", "nodes/proxy", "services", "endpoints", "pods"]
verbs: ["get", "list", "watch"]
- apiGroups: ["discovery.k8s.io"]
resources: ["endpointslices"]
verbs: ["get", "list", "watch"]
- apiGroups: ["networking.k8s.io"]
resources: ["ingresses"]
verbs: ["get", "list", "watch"]
- nonResourceURLs: ["/metrics", "/metrics/cadvisor"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: prometheus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: prometheus
subjects:
- kind: ServiceAccount
name: prometheus
namespace: monitoring
Grant only the verbs and resources the configured roles need: dropping ingresses when no ingress
role is used, for example, keeps the blast radius of a leaked token small.
kubernetes_sd_configs: the discovery roles
A kubernetes_sd_configs entry talks to the Kubernetes API server (in-cluster config is autodetected
from the service account mounted into the Prometheus pod) and re-runs on every change, so scrape
targets track the cluster’s actual state without a restart. Each entry declares exactly one role,
and the role determines both what gets listed as a target and which __meta_kubernetes_* labels are
attached for relabeling:
| Role | What it discovers and attaches |
|---|---|
|
One target per cluster node, addressed at the kubelet’s port. Attaches
|
|
One target per Service port, addressed at the Service’s ClusterIP. Rarely scraped
directly (a ClusterIP does not route to a specific pod’s metrics endpoint) but useful for blackbox
probing of the Service as a whole. Attaches |
|
One target per address in every |
|
One target per pod, per declared container port, regardless of whether a Service fronts it.
Attaches |
|
One target per |
Annotation-based scraping with the pod role
The common pattern is to scrape only pods that opt in via a prometheus.io/scrape: "true" annotation,
using the pod’s own prometheus.io/port and prometheus.io/path annotations (when set) to build the
final target address. This is plain relabel_configs work over the labels the pod role attaches — Service Discovery & Relabeling already
shows the base version of this pattern (the __ vs __meta_ prefix convention, the scrape/port-rewrite
keep/replace steps, and promoting namespace/pod to labels). The one addition this pattern needs on
top of that base is honoring an explicit prometheus.io/path annotation instead of always scraping the
default /metrics:
relabel_configs:
# ... the keep/port-rewrite/namespace/pod steps from the base pattern linked above, plus:
# Honor an explicit prometheus.io/path annotation, default to /metrics.
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
Applications opt in through pod annotations. The orders-api Deployment declares where its metrics are:
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: orders-api
template:
metadata:
labels:
app: orders-api
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: /actuator/prometheus
spec:
containers:
- name: orders-api
image: registry.example.com/orders-api:1.0.0
ports:
- containerPort: 8080
Annotation names reach relabeling with every non-alphanumeric character turned into an underscore
(prometheus.io/path becomes __meta_kubernetes_pod_annotation_prometheus_io_path). These annotations are a
convention implemented by the relabeling rules, not something Prometheus itself understands, so a pod
is scraped only when the keep rule says so.
Swap role: pod for role: endpointslice and the same annotation checks work against
__meta_kubernetes_endpointslice_*-sourced labels instead, scraping only the pods that back an
annotated Service. Container orchestration and the sidecar/DaemonSet layout that typically runs
Prometheus and its exporters in-cluster are covered in
Exporters & the Pushgateway; recording rules
that pre-aggregate the resulting per-pod series are in
Recording & Alerting Rules.
The complete scrape configuration
Put together, the three jobs of the example live in one prometheus.yml (kept in a ConfigMap and mounted
at /etc/prometheus). promtool check config accepts it:
global:
scrape_interval: 30s
evaluation_interval: 30s
scrape_configs:
- job_name: kubernetes-cadvisor
scheme: https
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
authorization:
credentials_file: /var/run/secrets/kubernetes.io/serviceaccount/token
kubernetes_sd_configs:
- role: node
relabel_configs:
- target_label: __address__
replacement: kubernetes.default.svc:443
- source_labels: [__meta_kubernetes_node_name]
regex: (.+)
target_label: __metrics_path__
replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor
- source_labels: [__meta_kubernetes_node_name]
target_label: node
- job_name: kube-state-metrics
kubernetes_sd_configs:
- role: endpointslice
namespaces:
names: [kube-system]
relabel_configs:
- source_labels: [__meta_kubernetes_service_name]
regex: kube-state-metrics
action: keep
- source_labels: [__meta_kubernetes_endpointslice_port_name]
regex: http-metrics
action: keep
- job_name: kubernetes-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
regex: "true"
action: keep
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
regex: (.+)
target_label: __metrics_path__
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
The Prometheus Deployment then mounts that ConfigMap, runs under the prometheus service account and uses the
management API for its probes (the same readiness and liveness endpoints described in
Security & Production Operations):
apiVersion: apps/v1
kind: Deployment
metadata:
name: prometheus
namespace: monitoring
spec:
replicas: 1
selector:
matchLabels:
app: prometheus
template:
metadata:
labels:
app: prometheus
spec:
serviceAccountName: prometheus
containers:
- name: prometheus
image: prom/prometheus:v3.5.0
args:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=15d
- --web.enable-lifecycle
ports:
- containerPort: 9090
readinessProbe:
httpGet: { path: /-/ready, port: 9090 }
livenessProbe:
httpGet: { path: /-/healthy, port: 9090 }
volumeMounts:
- { name: config, mountPath: /etc/prometheus }
- { name: data, mountPath: /prometheus }
volumes:
- name: config
configMap:
name: prometheus-config
- name: data
emptyDir: {}
An emptyDir loses its data when the pod is rescheduled; for anything beyond an experiment use a
PersistentVolumeClaim (a StatefulSet with a volume claim template), and remember that a single replica is
a single point of failure for scraping and alerting (see
Security & Production Operations for HA).
Operators such as the Prometheus Operator replace this hand-written scrape configuration with
ServiceMonitor and PodMonitor custom resources; they are an alternative packaging of the same
discovery and relabeling concepts and are not covered here.
kube-state-metrics: cluster-state metrics
kube-state-metrics is a separate service (deployed once per cluster, not per node) that watches the Kubernetes API and exposes the declared and observed state of objects as plain Prometheus metrics — it does not talk to the kubelet and carries no resource-usage numbers at all. Where cAdvisor answers "how much CPU/memory is this container using", kube-state-metrics answers "how many replicas does this Deployment want versus have" or "what phase is this pod in":
# Pods stuck outside the Running phase for more than 10 minutes.
kube_pod_status_phase{phase!="Running"} == 1
and on (namespace, pod)
(time() - kube_pod_created) > 600
# Deployments whose ready replica count has fallen behind the desired count.
kube_deployment_status_replicas_ready
< on (namespace, deployment)
kube_deployment_spec_replicas
The on (namespace, pod) is required: kube_pod_status_phase carries an extra phase label that
kube_pod_created does not have, so a plain and matches on the full label set and returns nothing
(a unit test with a pending pod confirmed that the bare form is empty and the on form returns the series).
Also note that a pod in any non-Running phase has the series for the other phases at 0, which is why
the expression selects == 1.
Deploy it as its own scrape target (a Deployment with a Service, discovered like any other workload via
the endpointslice or pod role above) rather than trying to derive cluster state from cAdvisor’s
per-container numbers, which have no concept of a Deployment’s desired replica count or a pod’s
scheduling phase. See kube-state-metrics for the
full metric catalog, deployment manifests, and versioning against Kubernetes releases.
Alerting on both sources together
The two sources answer different questions, so useful alerts usually join them. These rules for the
orders-api Deployment record per-pod CPU, alert when fewer replicas are available than desired, and alert
when a container’s working set approaches its memory limit:
groups:
- name: orders-api.kubernetes
rules:
- record: namespace_pod:container_cpu_usage:rate5m
expr: sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container!=""}[5m]))
- alert: OrdersApiReplicasUnavailable
expr: |
kube_deployment_spec_replicas{deployment="orders-api"}
> kube_deployment_status_replicas_available{deployment="orders-api"}
for: 10m
labels:
severity: page
team: orders
annotations:
summary: "{{ $labels.namespace }}/{{ $labels.deployment }} has fewer available replicas than desired"
- alert: OrdersApiMemoryNearLimit
expr: |
max by (namespace, pod, container) (container_memory_working_set_bytes{container="orders-api"})
/
max by (namespace, pod, container) (kube_pod_container_resource_limits{container="orders-api", resource="memory"})
> 0.9
for: 5m
labels:
severity: warning
team: orders
annotations:
summary: "{{ $labels.pod }} is using {{ $value | humanizePercentage }} of its memory limit"
promtool check rules accepts the file, and promtool test rules verified both alerts against synthetic
series: a Deployment wanting 2 replicas with 1 available fires after the 10-minute for, and a
pod whose working set climbs from 400 MB to 495 MB against a 512 MB limit fires with the annotation
orders-api-7d4b9-abcde is using 96.68% of its memory limit. The matching max by (...) on both sides
makes the division one-to-one even when cAdvisor reports extra labels (such as id or image) that
kube-state-metrics does not.
Continue with Exporters & the Pushgateway for how exporters like kube-state-metrics and node_exporter fit into a cluster’s overall scrape topology, or Prometheus & Monitoring for the section overview.