Inspecting containers: inspect, top, stats and events

Intermediate · 1 min

Read a container's config and state with docker inspect and Go templates, its processes with top, its live usage with stats and its history with events.

Before thisdocker run and the container lifecycleContainer logs and logging drivers

DevOps Directive · 12 min · from 3:06:58

Inspecting containers: inspect, top, stats and events

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps DirectiveReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • docker inspect returns the daemon's full JSON record of a container: its config, host config, state, mounts and network settings.
  • --format takes a Go template, so you can pull out one field, such as {{.State.ExitCode}} or {{.State.OOMKilled}}, instead of scrolling JSON.
  • docker top lists a container's processes as the host sees them, with host PIDs, which is how you match a container to what ps or top shows on the host.
  • docker stats reads the container's cgroup counters. Memory excludes reclaimable page cache, and CPU % is relative to one core, so 250% means two and a half cores.
  • docker events streams what the daemon does, including die with its exit code, oom and health_status changes, and is the record of what happened while you weren't watching.

“It’s running. What’s it doing?”

docker ps tells you a container is Up 3 hours. That’s not much when the service is slow, a container restarts every few minutes, or the host is out of memory and you need to know which container ate it. Four commands answer the next questions: how is it configured (inspect), what’s running inside (top), what is it using right now (stats), and what happened while nobody watched (events).

They’re like a car’s logbook, its engine bay, its dashboard and its dashcam.

docker inspect

docker inspect api prints the daemon’s JSON record for the container, the same object the Engine API returns from GET /containers/{id}/json. From the API spec, the top-level fields are:

Id Created Path Args State Image ResolvConfPath HostnamePath HostsPath LogPath Name
RestartCount Driver Platform ImageManifestDescriptor MountLabel ProcessLabel AppArmorProfile
ExecIDs HostConfig GraphDriver Storage SizeRw SizeRootFs Mounts Config NetworkSettings

Three sections matter most. Config is what the image and your flags asked for: Cmd, Entrypoint, Env, User, Labels, Healthcheck. HostConfig is how the host runs it: RestartPolicy, Memory, NanoCpus, PortBindings, LogConfig, Privileged. State is the live part: Status, Running, Paused, Restarting, OOMKilled, Dead, Pid, ExitCode, Error, StartedAt, FinishedAt and Health.

The JSON runs to hundreds of lines, so pull fields out with --format, which takes a Go template. These follow Docker’s formatting docs:

docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' api
docker inspect -f '{{.RestartCount}} restarts, last started {{.State.StartedAt}}' api
docker inspect -f '{{json .Mounts}}' api | jq
docker inspect -f '{{range .NetworkSettings.Networks}}{{println .IPAddress}}{{end}}' api
docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}}' api
docker inspect -f '{{.State.Pid}}' api        # the host PID of the container's PID 1

index is how you read a map key containing dots, and json re-encodes a sub-object for jq. inspect works on images, volumes and networks too, and --type settles ambiguous names. The last command bridges to the host: that PID is what you’d hand to nsenter -t in the namespaces lesson or look up in /proc.

docker top

docker top api runs ps against the container’s processes and shows them as the host sees them, with host PIDs. Anything after the name is passed as ps options, as in docker top api -o pid,rss,args. It’s the quickest way to answer “is the worker still alive?” or “what is PID 48213 on this host?” without needing ps inside the image.

docker stats

docker stats streams one row per running container: CPU %, memory used against the limit, network I/O, block I/O and PIDs. --no-stream prints one sample, and --format works like inspect:

docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.PIDs}}'

The numbers come from the container’s cgroup, and two calculations in the CLI’s source, stats_helpers.go, explain most confusion:

  • Memory is usage - inactive_file on cgroup v2. The CLI subtracts page cache the kernel could reclaim, so docker stats reads lower than the cgroup’s own memory.current.
  • CPU % is (container CPU delta / system CPU delta) × online CPUs × 100. As a worked example: a container using 1.7 s of CPU time in a 2-second sample on a 4-core host has a container delta of 1.7 s against a system delta of 8 s (4 cores × 2 s), and 1.7 / 8 × 4 × 100 = 85%. One fully busy core shows as 100%, so 340% on a 4-core host is normal.

stats is a live view with no history. For graphs and alerts you need a collector. Monitoring containers covers that.

docker events

docker events streams what the daemon does. Per the API spec, containers report attach, commit, copy, create, destroy, detach, die, exec_create, exec_detach, exec_start, exec_die, export, health_status, kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update and prune. Images, volumes and networks report their own.

docker events --since 30m --filter container=api
docker events --filter event=die --filter event=oom --format '{{json .}}'

A die event carries the exitCode in its attributes, and Engine 29.10 added a restarting attribute that says whether the restart policy will bring it back. An oom event right before a die with code 137 settles an argument fast. The reference warns that only the last 256 events are replayed with --since. For a real record, ship the stream somewhere.

About the video

The embed is the “Interacting with Docker objects” chapter of DevOps Directive’s “Complete Docker Course - From BEGINNER to PRO!”, April 2023, from 3:06:58 to 3:18:36, 12 minutes. Per the course’s companion written lesson, it tours the subcommands for images, containers, volumes and networks, including inspect, top, logs, attach, exec, stop and kill, ls, prune and wait. That’s a broader tour than this lesson. It doesn’t go into Go templates, the stats formulas or events. Some of it, like docker scan, has since been replaced, by Docker Scout. English was judged from the channel and its English caption track. Darshan Builds in deeper covers inspect templates, OOM kills and exit codes, from a small new channel.

What was run: the inspect field lists and the event list were read from the Engine API’s swagger.yaml (v1.57), and the CPU and memory formulas from docker/cli’s stats_helpers.go. The CPU figure above is arithmetic on example numbers, not a measurement. Nothing ran in Docker. Checked 2026-11-28.

Where this fits

Next, keeping containers up without watching them: restart policies and health checks.

Check yourself

  1. 01A container keeps restarting and docker logs shows nothing useful. Which inspect fields tell you why it died?

    State.ExitCode, State.OOMKilled, State.Error, State.FinishedAt and RestartCount, for example docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}} {{.RestartCount}}' api.

  2. 02docker stats shows 800 MiB used, but the cgroup's memory.current reads 1.2 GiB. Which is wrong?

    Neither. The CLI subtracts inactive_file, page cache the kernel can reclaim, from the cgroup's usage. memory.current includes that cache.

  3. 03On a 4-core host, docker stats shows a container at 340% CPU. Is that an error?

    No. The CLI scales the percentage by the number of online CPUs, so 100% is one full core and 340% is about three and a half cores busy.

  4. 04A container was OOM-killed at 3 a.m. and has restarted since. How can you see that it happened?

    docker events --since with a filter on the container shows the oom and die events with timestamps, and inspect's RestartCount shows it restarted. The daemon only replays the last 256 events, so ship them somewhere if you need history.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark