Skip to content

cAdvisor explained: what it exposes, when you need it, and the Prometheus setup that works

cAdvisor reads cgroup accounting and exposes per-container CPU, memory, network and filesystem metrics to Prometheus. What each container_ family means, how to run cAdvisor on Docker and containerd, and when the kubelet already gives you the same data.

cAdvisor (Container Advisor) is a small Go agent, maintained by Google, that reads the kernel’s cgroup accounting files and talks to the container runtime, then publishes per-container CPU, memory, network and filesystem counters on an HTTP endpoint in Prometheus exposition format. You run it standalone on plain Docker or containerd hosts, where nothing else can tell you which of your forty containers is responsible for the host being at 80% CPU. On Kubernetes you almost certainly should not: the kubelet embeds cAdvisor and already serves the same container_* families at /metrics/cadvisor, so a separate deployment duplicates the data and doubles the series count.

What you’ll accomplish

  • cAdvisor running as a read-only container on a Docker or containerd host, bound to loopback rather than the public interface.
  • A Prometheus scrape job that keeps the container_* families dashboards actually read, and drops the rest before they reach storage.
  • Four PromQL queries that answer the questions people actually ask during an incident: is this container being throttled, is it close to its memory limit, is it restarting, is its filesystem filling up.
  • A sanity check that ties a PromQL result back to what docker stats reports for the same container.
  • A clear rule for the hosts where you should skip cAdvisor entirely.

Prerequisites

You need Docker 20.10 or newer, or containerd 1.6 or newer, on a host you have root on. cAdvisor mounts host paths read-only and reads /dev/kmsg, so this is not something you can run as an unprivileged user.

You need to know which cgroup version the host uses, because it changes what cAdvisor reads and what it can report:

stat -fc %T /sys/fs/cgroup
cgroup2fs

cgroup2fs means the unified hierarchy — the default on Ubuntu 22.04 and later, Debian 12, RHEL 9 and Fedora. tmpfs means cgroup v1, with a separate directory per controller under /sys/fs/cgroup/cpu, /sys/fs/cgroup/memory and so on.

The practical differences: on v1, cAdvisor reads memory.usage_in_bytes and cpuacct.usage; on v2 it reads memory.current, memory.stat, cpu.stat and io.stat from one unified tree. Most of the metric names you care about are identical across both. A handful of v1-only counters have no v2 equivalent — container_memory_failcnt maps to v1’s memory.failcnt and simply stays flat on a v2 host — and CPU throttling counters move from cpu.cfs_* fields under the cpu controller directory to the nr_throttled and throttled_usec fields of the unified cpu.stat. Use cAdvisor v0.45 or later on a v2 host; earlier releases had partial v2 support. Our cgroup v2 resource control article covers the file layout in detail.

You also need a reachable Prometheus instance. And if the host is a Kubernetes node, stop here: skip the install and scrape the kubelet instead — see the last section.

How it works

cAdvisor runs a housekeeping loop. On each pass it enumerates the containers it can see — through the Docker socket at /var/run/docker.sock, through the CRI socket for containerd, or by walking the cgroup tree directly — and for each one it reads the accounting files the kernel maintains as a side effect of resource control. Nothing is sampled from inside the container, and nothing is injected into it. cAdvisor is a reader.

Those readings are cached in memory and rendered on demand at /metrics in Prometheus text format. Prometheus scrapes that endpoint on its own interval, so the freshness of a metric is bounded by the slower of the two: a 15s scrape against a 30s housekeeping interval gives you 30s-old numbers.

Data path from kernel cgroup files through cAdvisor to a Prometheus alert

The families worth knowing, and what they mean:

  • CPU. container_cpu_usage_seconds_total is a counter of CPU-seconds consumed, so rate() over it yields cores. container_cpu_user_seconds_total and container_cpu_system_seconds_total split that by mode. container_cpu_cfs_periods_total, container_cpu_cfs_throttled_periods_total and container_cpu_cfs_throttled_seconds_total come from the CFS bandwidth controller and are the only honest way to tell whether a CPU limit is hurting you.
  • Memory. container_memory_working_set_bytes is usage minus inactive file cache — the number the kernel’s OOM killer effectively looks at, and the one to compare against a limit. container_memory_usage_bytes includes reclaimable page cache and will alarm you for no reason. container_memory_rss and container_memory_cache give the breakdown. container_spec_memory_limit_bytes reports the configured limit, and is 0 when no limit is set.
  • Network. container_network_receive_bytes_total and container_network_transmit_bytes_total per interface, plus matching _errors_total and _dropped_total counters.
  • Filesystem. container_fs_usage_bytes and container_fs_limit_bytes per device, plus container_fs_reads_bytes_total and container_fs_writes_bytes_total.
  • Lifecycle. container_start_time_seconds, container_last_seen and container_oom_events_total.
  • Machine. machine_cpu_cores and machine_memory_bytes describe the host, which is what lets you express container usage as a fraction of the box.

The upstream flag reference and metric list live in the cAdvisor repository.

Step-by-step

  1. Run cAdvisor as a container with read-only mounts. Publish on loopback only; let Prometheus reach it over a private network or a node firewall rule rather than exposing 8080 to the internet.

    docker run -d \
      --name cadvisor \
      --restart unless-stopped \
      --publish 127.0.0.1:8080:8080 \
      --volume /:/rootfs:ro \
      --volume /var/run:/var/run:ro \
      --volume /sys:/sys:ro \
      --volume /sys/fs/cgroup:/sys/fs/cgroup:ro \
      --volume /var/lib/docker/:/var/lib/docker:ro \
      --volume /dev/disk/:/dev/disk:ro \
      --device /dev/kmsg \
      --privileged \
      gcr.io/cadvisor/cadvisor:v0.49.1 \
      --housekeeping_interval=30s \
      --docker_only=true \
      --store_container_labels=false \
      --enable_metrics=cpu,memory,diskIO,disk,network,oom_event
    e3f1a9c4d7b2085f6c1e4a9d0b73f5c2a81e6d4f39b7c05a2e8d1f6b4c93a70e

    The explicit /sys/fs/cgroup mount matters on cgroup v2 hosts; without it cAdvisor sees the root cgroup and little else. --device /dev/kmsg is what makes OOM events visible. --docker_only=true skips the system slices, and --store_container_labels=false stops every image label from becoming a Prometheus label.

  2. Confirm the container is up and seeing workloads.

    docker ps --filter name=cadvisor --format 'table {{.Names}}\t{{.Status}}'
    NAMES      STATUS
    cadvisor   Up 41 seconds
  3. Curl /metrics and read what it actually returns. The count tells you how much you are about to ask Prometheus to store, per host, per scrape.

    curl -fsS http://127.0.0.1:8080/metrics | grep -c '^container_'
    1843
    curl -fsS http://127.0.0.1:8080/metrics | grep '^container_memory_working_set_bytes' | head -2
    container_memory_working_set_bytes{id="/docker/4b8f1c",image="nginx:1.27-alpine",name="web"} 2.5559040e+07
    container_memory_working_set_bytes{id="/docker/a71e93",image="postgres:16",name="db"} 4.11041792e+08

    The label set is trimmed above for readability; the real output carries more. Note the name label — that is the Docker container name, and it is what most dashboards group by. Rows with an empty name are the parent cgroup slices that aggregate their children, and double-count if you sum across them.

  4. Add the Prometheus scrape job. A keep rule is more predictable than a list of drops: you decide what enters storage, and a new cAdvisor release adding twelve metric families does not silently change your bill.

    scrape_configs:
      - job_name: 'cadvisor'
        scrape_interval: 30s
        static_configs:
          - targets:
              - 'host01.internal:8080'
              - 'host02.internal:8080'
            labels:
              env: 'prod'
        metric_relabel_configs:
          # Keep only the families dashboards and alerts read
          - source_labels: [__name__]
            regex: 'container_(cpu_usage_seconds_total|cpu_cfs_(periods|throttled_periods|throttled_seconds)_total|memory_working_set_bytes|memory_rss|spec_memory_limit_bytes|network_(receive|transmit)_bytes_total|fs_(usage|limit)_bytes|start_time_seconds|last_seen|oom_events_total)'
            action: keep
          # Drop the aggregate cgroup rows that carry no container name
          - source_labels: [name]
            regex: ''
            action: drop

    Validate before reloading — a bad regex here silently drops everything:

    promtool check config /etc/prometheus/prometheus.yml
    Checking /etc/prometheus/prometheus.yml
      SUCCESS: 0 rule files found
     SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax

    The full relabelling semantics are in the Prometheus configuration reference.

  5. Write the four queries worth keeping. Everything else is a variation on these.

    # 1. CFS throttling ratio per container; 0 means never throttled
    sum by (name) (rate(container_cpu_cfs_throttled_periods_total{name!=""}[5m]))
      /
    sum by (name) (rate(container_cpu_cfs_periods_total{name!=""}[5m]))
    
    # 2. Working set as a fraction of the container's own memory limit
    container_memory_working_set_bytes{name!=""}
      /
    (container_spec_memory_limit_bytes{name!=""} > 0)
    
    # 3. Restarts in the last hour; cAdvisor has no restart counter
    changes(container_start_time_seconds{name!=""}[1h])
    
    # 4. Filesystem usage per container against its limit
    container_fs_usage_bytes{name!=""} / container_fs_limit_bytes{name!=""}

    Query 1 is the one people miss. A container pinned at its CPU quota looks perfectly healthy on a usage graph — usage is flat because the quota is flat — and only the throttling ratio shows that requests are queuing behind the scheduler. Query 2 uses the > 0 filter to exclude unlimited containers, where the limit is reported as a very large sentinel value rather than as absent. Query 3 works because container_start_time_seconds is a gauge that changes when the container is recreated; changes() counts those transitions.

  6. Cap what cAdvisor costs you. On a host with 200 containers, the default configuration is genuinely expensive: cAdvisor walks every cgroup on every housekeeping pass, and CPU use scales with container count times metric count. The levers, in order of effect:

    docker run ... gcr.io/cadvisor/cadvisor:v0.49.1 \
      --housekeeping_interval=30s \
      --max_housekeeping_interval=60s \
      --allow_dynamic_housekeeping=true \
      --docker_only=true \
      --store_container_labels=false \
      --whitelisted_container_labels=com.docker.compose.service \
      --enable_metrics=cpu,memory,diskIO,disk,network,oom_event \
      --event_storage_event_limit=default=0 \
      --event_storage_age_limit=default=0

    --allow_dynamic_housekeeping lets cAdvisor back off on idle containers. --enable_metrics is an allowlist: leaving out percpu, hugetlb, referenced_memory, cpu_topology, resctrl, tcp and udp removes the families with the worst cardinality-to-value ratio. Budget roughly a tenth of a core and a few hundred megabytes of RSS for a busy host, and measure rather than assume — cAdvisor exposes its own process metrics on the same endpoint.

Validate it works

Three checks, in order. First, Prometheus has the target and it is healthy:

curl -fsS 'http://127.0.0.1:9090/api/v1/targets?state=active' \
  | jq -r '.data.activeTargets[] | select(.scrapePool=="cadvisor") | "\(.scrapeUrl) \(.health) \(.lastError)"'
http://host01.internal:8080/metrics up
http://host02.internal:8080/metrics up

Second, a container_ series is actually returning data rather than an empty result:

curl -fsS 'http://127.0.0.1:9090/api/v1/query' \
  --data-urlencode 'query=sum by (name) (rate(container_cpu_usage_seconds_total{name!=""}[5m]))' \
  | jq -r '.data.result[] | "\(.metric.name) \(.value[1])"'
web 0.0412
db 0.1873

Third — the check that catches misconfiguration nothing else does — compare that against the runtime’s own view on the same host:

docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'
NAME      CPU %     MEM USAGE / LIMIT
web       4.11%     24.38MiB / 512MiB
db        18.62%    392MiB / 2GiB

A PromQL rate of 0.0412 cores against a docker stats reading of 4.11% is the same number expressed two ways, and 24.38MiB lines up with the 2.5559040e+07 bytes from step 3. If the two disagree by more than a rounding margin, your rate window is longer than the spike you are looking at, or you are summing parent cgroup slices along with their children.

Troubleshooting

No container_* metrics at all, or only a single row for /. Almost always the cgroup v2 mount. Add --volume /sys/fs/cgroup:/sys/fs/cgroup:ro explicitly rather than relying on the /sys mount, and confirm the version with stat -fc %T /sys/fs/cgroup. If you are on a cAdvisor image older than v0.45 on a v2 host, upgrade first — the older releases read v1 paths that do not exist.

Empty name and image labels on a containerd host. Those two labels are populated from the Docker API. On a containerd-only host cAdvisor falls back to the cgroup path in the id label and to CRI annotations, and --docker_only=true makes it skip those cgroups entirely. Drop that flag on containerd hosts, key your dashboards off id or the pod and container labels instead of name, and adjust the name drop rule in step 4 accordingly.

cAdvisor itself is the top CPU consumer. This is real on hosts with hundreds of short-lived containers, where housekeeping never finishes before the next pass starts. Raise --housekeeping_interval to 30s or 60s, turn on --allow_dynamic_housekeeping, and trim --enable_metrics to the families you query. If it is still expensive, the host has more churn than a polling collector suits, and the runtime’s own event stream is a better fit.

Cardinality climbing with every deploy. Two causes. Image and VCS labels turn into Prometheus labels when --store_container_labels is left at its default, so every build changes the label set and creates a new series; set it to false and allow only the labels you need with --whitelisted_container_labels. Separately, the id label contains the container ID, so every docker run mints a fresh series — churn from CI runners and cron containers accumulates in the index even after the series go stale. If you are already fighting a series budget, Prometheus federation and cardinality budgets covers the accounting side.

Duplicate series after adding a Kubernetes cluster. If you scrape both a cAdvisor DaemonSet and the kubelet’s /metrics/cadvisor, every container reports twice under different job and instance labels. Storage doubles, and any sum without a job filter double-counts — which is worse than an obvious outage because the dashboard still looks plausible. Pick one source per node.

When this is the wrong approach

On Kubernetes, the kubelet already embeds cAdvisor and exposes the same metrics at https://<node>:10250/metrics/cadvisor, reachable through the API server proxy with a service account token. Running a separate cAdvisor DaemonSet there buys you a slightly newer cAdvisor version and costs you a duplicate copy of every container series. The default answer is to scrape the kubelet.

cAdvisor is also not an APM. It measures the box the process lives in, not the process: no request latency, no error rates, no slow query log, no traces, no stack-level attribution. It will tell you a container is throttled; it will not tell you which endpoint got slow because of it. And it does not know what a Pod is — restart counts, phase and readiness come from kube-state-metrics, not from cgroup accounting. Host-level CPU, memory and disk belong to node_exporter, which is a complement to cAdvisor rather than an alternative.

Coverage map showing which of node_exporter, cAdvisor and the kubelet supplies each metric family

The short version: node_exporter for the host, cAdvisor or the kubelet (never both) for the containers, kube-state-metrics for Kubernetes object state, and your own instrumentation for anything about requests.

If alerts fire into an empty room after hours, that’s exactly what 24/7 Monitoring & Response closes — book a monitoring and response review.