Chapter 11 · Lesson 9 of 10
Monitoring and logs

Container metrics with cAdvisor and docker stats

docker stats shows live per-container CPU and memory in the terminal, while cAdvisor exports the same data as Prometheus metrics so you can graph and alert on each container.

By the end you will

Read container usage with docker stats and scrape cAdvisor from Prometheus without exposing its port.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • Docker installed on the server
  • Prometheus running, see the Prometheus lesson

docker stats gives you a live table of CPU and memory per container, with --no-stream and --format for scripts. cAdvisor runs as a container, reads usage from the host and serves it as Prometheus metrics, so you can graph container_memory_working_set_bytes and rate(container_cpu_usage_seconds_total[5m]) per container. Keep its port on localhost or a private network.

How it works#

Linux control groups (cgroups) record the CPU, memory, network and disk used by each container. docker stats asks the Docker daemon for those numbers and prints them. cAdvisor reads the same host data directly and exposes it at /metrics, with a label per container, so Prometheus can scrape and store it over time. Host-level metrics from node_exporter, covered in Prometheus and node exporter basics, tell you the server is low on memory. cAdvisor tells you which container is responsible. See the glossary entry for container if the term is new.

Step 1: Use docker stats#

bash
docker stats

The table refreshes until you press Ctrl+C. Columns include CPU percent, memory usage against its limit, network and block I/O and the number of processes. For a single reading:

bash
docker stats --no-stream
docker stats --no-stream --format "{{.Name}} {{.CPUPerc}} {{.MemUsage}}"

--no-stream prints once and exits, so cron and scripts can use it. --format takes a Go template. If a container has no memory limit, the limit column shows the host’s total memory, so a container can use much more than you intended. Limits are set with --memory or in Compose, as shown in docker compose basics.

Step 2: Run cAdvisor#

cAdvisor needs read-only access to host information. This Compose service follows the example in the cAdvisor project README:

yaml
services:
  cadvisor:
    image: gcr.io/cadvisor/cadvisor:v0.49.1
    container_name: cadvisor
    restart: unless-stopped
    ports:
      - "127.0.0.1:8080:8080"
    volumes:
      - /:/rootfs:ro
      - /var/run:/var/run:ro
      - /sys:/sys:ro
      - /var/lib/docker/:/var/lib/docker:ro
    privileged: true
    devices:
      - /dev/kmsg

The mounts give it read access to the host root, runtime sockets, /sys for cgroup data and Docker’s data directory. Check the README for your version, since the exact list can change, and pin the tag you tested instead of latest. The privileged setting is broad, so only run cAdvisor on hosts you control and keep the port off the public network. A restart policy is explained in Docker restart policies.

The port binds to 127.0.0.1:8080. cAdvisor has a web UI and a metrics page that list every container, image name and mount with no login. Do not publish it as 8080:8080, which listens on all interfaces. See publish container ports safely.

Step 3: Scrape it from Prometheus#

Add a job to prometheus.yml:

yaml
  - job_name: cadvisor
    static_configs:
      - targets: ["127.0.0.1:8080"]

If Prometheus runs in Docker, put both on a shared Docker network and use cadvisor:8080 as the target instead. Validate and restart:

bash
promtool check config /etc/prometheus/prometheus.yml
sudo systemctl restart prometheus

Look for the cadvisor job on the targets page, and confirm it is UP.

Step 4: Query container metrics#

output
rate(container_cpu_usage_seconds_total{name!=""}[5m])
container_memory_working_set_bytes{name!=""}

The first gives CPU cores used per container. A value of 0.5 means half a core. The second is memory the container actively uses, which is the figure closest to what triggers an out-of-memory kill and is better than raw usage that includes cache. The filter name!="" drops cgroup entries that are not named containers. Graph these in Grafana as in Grafana dashboards for CPU, memory and disk, and compare against the limit to alert before a container hits it.

Check it worked#

  • docker stats --no-stream lists each running container with believable numbers.
  • docker ps --filter name=cadvisor shows the port bound to 127.0.0.1.
  • curl -s http://127.0.0.1:8080/metrics | grep container_memory_working_set_bytes prints lines.
  • The cadvisor target is UP in Prometheus.
  • From another machine, curl --max-time 5 http://203.0.113.10:8080/metrics fails.

Edge cases and gotchas#

  • No limit, no meaning. Without a memory limit, “percent of limit” is percent of the host. Set limits for containers you want to alert on.
  • Docker CPU percent can exceed 100. It counts per core, so 200 percent means two cores busy.
  • Metric labels vary by setup. Container names appear in name or container_label_* depending on the runtime and flags. Check your own /metrics output.
  • cAdvisor is heavy on busy hosts. It adds its own CPU and memory use, so watch it and consider fewer collected metrics on tiny servers.
  • Privileged container. Treat the host as trusted-only and keep the cAdvisor image and its port locked down.
  • Short-lived containers. One-off jobs vanish before a scrape. Their series stop, so a missing container is not always a failure.

Troubleshooting#

SymptomLikely causeFix
Cannot connect to the Docker daemon at unix:///var/run/docker.sockDocker not running or no permissionStart Docker and use sudo or the docker group
docker stats shows -- for valuesContainer just started or stoppedWait a few seconds and run it again
cAdvisor target DOWN with connection refusedWrong address or container not upCheck docker ps and the target address
No name label on metricsDocker data mount missingMount /var/lib/docker read-only as in the example
bind: address already in use on 8080Another service uses 8080Choose another host port, see fix port already in use
Metrics for containers are emptycgroup layout not readableCheck the README for your OS and cgroup version
Port 8080 reachable from the internetPublished on all interfacesBind to 127.0.0.1 and check the firewall
Memory seems too highUsing raw usage including cacheUse container_memory_working_set_bytes

Quick reference#

bash
docker stats --no-stream
docker stats --no-stream --format "{{.Name}} {{.CPUPerc}} {{.MemUsage}}"
curl -s http://127.0.0.1:8080/metrics | grep container_memory_working_set_bytes
output
rate(container_cpu_usage_seconds_total{name!=""}[5m])
container_memory_working_set_bytes{name!=""}

Related post: Docker container restarting in a loop.

Next#

Show users the result in build a public status page.

Try it: Watch container usage with docker stats

Take a snapshot of container CPU and memory, shape the output and see what cAdvisor is doing.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which flag makes docker stats print once and exit?
2What does rate(container_cpu_usage_seconds_total[5m]) return?
3Why does cAdvisor need read-only mounts of host paths like /sys and /var/lib/docker?
4Where should cAdvisor's port be reachable from?

Frequently asked questions

How do I see CPU and memory per container?

Run docker stats. It prints a live table with CPU percent, memory usage and limit, network and block I/O for every running container. Add --no-stream for a single snapshot.

How do I get docker stats output once for a script?

Use docker stats --no-stream --format "{{.Name}} {{.CPUPerc}} {{.MemUsage}}". The --format flag takes a Go template with the columns you want.

What is cAdvisor?

cAdvisor is a Google-developed container advisor that reads usage from the host and exposes per-container metrics at /metrics for Prometheus.

Which cAdvisor metric shows container memory?

container_memory_working_set_bytes is the usual one for memory pressure, since it excludes reclaimable cache. For CPU use rate on container_cpu_usage_seconds_total.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios