How do docker stats, docker inspect, and docker top monitor container metrics?
❓ Interview Prompt: Explain the monitoring capabilities of docker stats (live metrics), docker inspect (configuration JSON), and docker top (process list).
Docker provides three built-in monitoring commands that cover different dimensions of container observability:
1. docker stats — Live Resource Metrics:
Displays a continuously updating table of real-time performance metrics per container. Data comes from Linux cgroup counters.
Columns: CONTAINER, CPU %, MEM USAGE/LIMIT, MEM %, NET I/O, BLOCK I/O, PIDS.
2. docker inspect — Configuration & State Metadata:
Returns a comprehensive JSON document with every piece of container configuration: image ID, network settings, mounts, environment variables, restart count, health status, and more. Scriptable with Go templates or jq.
3. docker top — Process Table:
Lists all processes running inside the container from the host's perspective (wraps ps with the container's pid namespace). Useful for verifying that exactly one process is running as the non-root user.
Limitations:
These are single-host tools. For production at scale, use Prometheus + Grafana with cAdvisor for multi-host container metrics.
Code Implementation Example
# Live streaming stats for all containers
docker stats
# CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
# a3f1b2c4d5e6 api 8.2% 234MiB / 512MiB 45.7% 1.2MB / 890kB 0B / 0B
# One-shot (no streaming) for scripting
docker stats --no-stream --format "table {{.Name}} {{.CPUPerc}} {{.MemUsage}}"
# Inspect — extract specific fields with Go templates
docker inspect api --format '{{.State.Status}}'
docker inspect api --format '{{.NetworkSettings.Networks.bridge.IPAddress}}'
docker inspect api --format '{{.RestartCount}}'
# Full JSON piped to jq
docker inspect api | jq '.[0].Config.Env'
# Process list inside container
docker top api
# UID PID PPID CMD
# 1001 12345 12300 node server.js ← non-root UID 1001docker stats is for live resource monitoring; docker inspect is for configuration auditing; docker top is for process verification. Use Prometheus+cAdvisor for production-scale metrics.