Monitor Docker container memory and CPU usage: docker stats, sorting, limits, alerts
docker stats has no --sort flag. One pipe sorts containers by memory or CPU. Then read the numbers right, tell a leak from cache, and set limits.
By Shanky Gupta, Director of Softuvo Solutions (LinkedIn) · Published · Updated
Your app slows to a crawl at 2 a.m. and you need to know which container is eating the memory. docker stats shows it, but it has no --sort flag (still true in Docker 29), so on a host with 20 containers the biggest one is buried in the list. One pipe through sort fixes that. Below: the exact commands to sort docker stats by memory or CPU, how to read the numbers correctly, how to tell a leak from cache, and how to set limits so the OOM killer does not pick the wrong container.
How to sort docker stats by memory
Take one snapshot with --no-stream, print memory first with --format, and sort it. sort -h understands MiB and GiB, so 4.2GiB lands above 900MiB:
docker stats --no-stream --format '{{.MemUsage}}\t{{.Name}}' | sort -hr | head -10That ranks containers by how much memory they actually use. To rank them by how close they are to their own limit (the number that predicts an OOM kill), sort on the percentage instead:
docker stats --no-stream --format '{{.MemPerc}}\t{{.MemUsage}}\t{{.Name}}' | sort -rn | head -10The two orders are often different. On one of our hosts a database used 4.2 GiB (27% of 15 GiB, no limit set) while a web container used only 188 MiB, but that was 18% of its 1 GiB limit. Sort by usage to find what is filling the host; sort by percentage to find what will be killed first.
- Keep the header row: docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}' | (sed -u 1q; sort -k2 -hr)
- Sort by CPU instead: docker stats --no-stream --format '{{.CPUPerc}}\t{{.Name}}' | sort -rn | head
- Live, re-sorted every 5 seconds: watch -n 5 "docker stats --no-stream --format '{{.MemUsage}}\t{{.Name}}' | sort -hr | head"
- Only one Compose project: docker stats --no-stream $(docker compose ps -q) --format '{{.MemUsage}}\t{{.Name}}' | sort -hr
- Prefer clicking? ctop and lazydocker are terminal UIs that sort containers by memory or CPU interactively
Why plain docker stats cannot do this: its live mode redraws the screen in place, and sort needs the full output before it can print anything. That is why every sorted version uses --no-stream (one snapshot), and watch when you want it to keep refreshing.
docker stats --format placeholders
These are the fields you can put in --format, in any order. Put the one you want to sort by first so sort can use it without extra flags:
- {{.Name}} and {{.ID}}: container name and short ID ({{.Container}} prints whichever you passed)
- {{.CPUPerc}}: CPU use, where 100% is one full core
- {{.MemUsage}}: memory used / limit, e.g. 188MiB / 1GiB
- {{.MemPerc}}: memory used as a percentage of the limit
- {{.NetIO}} and {{.BlockIO}}: network and disk bytes read / written since the container started
- {{.PIDs}}: number of processes or threads in the container
- Prefix with table (--format 'table {{.Name}}\t{{.MemUsage}}') to get column headers
The Quickest Starting Point: docker stats
Docker ships with a live stats command that works immediately, no extra software required. Run it and you get a continuously refreshing table of every running container:
- docker stats: streams live CPU %, memory usage vs. limit, network I/O and block I/O for all running containers
- docker stats <container_name_or_id>: scope it to one or more containers
- docker stats -a: include stopped containers (they show 0)
- docker stats --no-stream: print a single snapshot and exit, for scripts, cron jobs and sorting
The CPU percentage shown is relative to a single core. On a 4-core host, 100% means one full core is saturated. Keep that in mind when reading numbers above 100% — your container is consuming more than one core, not breaking mathematics.
Reading the Memory Numbers Correctly
Memory output looks like '210MiB / 1.95GiB'. The first number is the container's current RSS-style usage; the second is its limit (or the host's total RAM if no limit is set). A container with no memory limit will happily consume all available RAM before the kernel OOM-killer starts terminating processes — usually the worst possible time to discover this.
Always set memory limits on production containers. Without them, a single runaway process can starve every other service on the host.
Set a hard limit at run time with --memory and a soft warning threshold with --memory-reservation:
- docker run --memory=512m --memory-reservation=400m your-image: a hard 512 MB ceiling, with the kernel reclaiming back towards 400 MB when the host is short of memory
- docker update --memory=512m --memory-swap=512m <container>: add or change a limit on a running container without recreating it
- docker inspect -f '{{.HostConfig.Memory}}' <container>: the limit in bytes (0 means no limit)
- cat /sys/fs/cgroup/system.slice/docker-<full_container_id>.scope/memory.current: raw usage on cgroup v2 hosts (most current distros); older cgroup v1 hosts use /sys/fs/cgroup/memory/docker/<id>/memory.usage_in_bytes
Leak or cache? Reading what is behind the number
docker stats already subtracts most of the page cache, so its number is close to what the container really needs. When it keeps growing, look at the cgroup's memory.stat to see what kind of memory is growing: anon is memory the processes allocated themselves, file is cached file data the kernel can drop under pressure.
id=$(docker inspect -f '{{.Id}}' <container>)
grep -E '^(anon|file) ' /sys/fs/cgroup/system.slice/docker-$id.scope/memory.stat- anon climbing for hours with no plateau, even when traffic is flat: a leak in the application
- file climbing while anon stays flat: cache from reading or writing files; the kernel frees it when needed, so this is usually harmless
- Both flat but the container still gets OOM-killed: the limit is simply too low for normal peaks; raise it or reduce worker counts
If docker stats shows 0B / 0B for memory, the memory cgroup controller is not enabled on the host. This is common on Raspberry Pi OS: add cgroup_enable=memory cgroup_memory=1 to /boot/cmdline.txt and reboot.
Capturing Historical Data with docker stats and Simple Scripts
docker stats is great for real-time debugging but terrible for answering 'what was happening at 2 a.m.?' For historical data without standing up a full monitoring stack, a small shell loop written to a log file is often enough to start:
- while true; do docker stats --no-stream --format "$(date +%FT%T),{{.Name}},{{.CPUPerc}},{{.MemUsage}}" >> /var/log/container-stats.csv; sleep 30; done: logs a timestamped CSV snapshot every 30 seconds
- Run it inside a tmux or screen session, or as a systemd service, so it survives SSH disconnects
- Pipe output to grep or awk to filter for specific containers in high-container-count environments
This is not a replacement for proper time-series storage, but it gives you a simple audit trail you can grep through when something goes wrong.
Going Deeper: cAdvisor and Prometheus
If your team is ready for a more complete solution, Google's cAdvisor (Container Advisor) is the standard open-source exporter for Docker metrics. It runs as a container itself, scrapes cgroup data, and exposes a Prometheus-compatible endpoint:
- docker run --volume=/var/run:/var/run:ro --volume=/sys:/sys:ro --volume=/var/lib/docker/:/var/lib/docker:ro --publish=8080:8080 --detach=true --name=cadvisor gcr.io/cadvisor/cadvisor — starts cAdvisor with read-only host access
- Browse http://localhost:8080/containers/ for a built-in web UI with CPU and memory graphs
- Scrape http://localhost:8080/metrics from Prometheus for long-term storage and alerting
- Key metrics to watch: container_cpu_usage_seconds_total, container_memory_usage_bytes, container_memory_working_set_bytes (working set is usually more meaningful than raw usage)
Pair cAdvisor with Grafana and you have a full dashboard. The setup takes an afternoon but pays for itself the first time you need to correlate a deploy with a memory spike hours later.
What to Actually Alert On
Collecting data is only half the job — you need to know when to wake someone up. Focus on these thresholds as a practical starting point:
- CPU sustained above 80% for more than 5 minutes — a brief spike is normal; sustained high CPU usually signals a stuck process or traffic anomaly
- Memory usage above 90% of the container limit — at this point OOM-kills are close; investigate before the kernel does it for you
- Memory usage growing steadily over hours with no plateau — classic memory leak signature
- Container restart count increasing — docker inspect <container> | grep RestartCount will show you; repeated restarts mean something is crashing silently
If managing these thresholds across multiple containers sounds tedious, that's exactly the gap tools like Opservo are built to fill — it watches your containers continuously, surfaces anomalies in plain English, and flags the signals that actually matter before they become incidents. For small teams without a dedicated ops person, that kind of automated context can be the difference between catching a problem at 9 a.m. and getting paged at 2 a.m.
Start with docker stats today. Add cgroup limits to every production container this week. When you're ready for historical data and intelligent alerting, build from there — the foundation you lay now makes every future improvement much easier.
Read next in the server health and monitoring series: Redis memory usage and eviction: how to monitor it before keys start disappearing and How do you monitor Docker containers on a VPS?. The whole series is at Server health and monitoring.