docker, updated

docker inspect: find what you need in the JSON

Get single values out of docker inspect with Go templates and jq: IPs, ports, mounts, env, health, log path, and audit one-liners for privileged containers and docker.sock mounts.

What it inspects

docker inspect prints the full configuration and state as a JSON array, one element per object. It works on containers, images, networks and volumes; with an ambiguous name, pick the type.

ObjectCommand
Containerdocker inspect web
Several at oncedocker inspect web db
All running containersdocker inspect $(docker ps -q)
Imagedocker image inspect nginx:1.27 (or docker inspect --type image nginx)
Networkdocker network inspect appnet
Volumedocker volume inspect pgdata
Container with disk size (SizeRw, SizeRootFs)docker inspect -s web

Where things are

The top-level keys of a container, and what to look for in them:

KeyHolds
StateStatus, Running, Pid, ExitCode, OOMKilled, StartedAt, Health
ConfigWhat the image and docker run defined: Image, Env, Cmd, Entrypoint, User, Labels, ExposedPorts, Healthcheck
HostConfigHow it runs on this host: Binds, PortBindings, RestartPolicy, Privileged, CapAdd, NetworkMode, PidMode, LogConfig, Memory, ReadonlyRootfs, SecurityOpt
NetworkSettingsNetworks (per network: IPAddress, Gateway, MacAddress, Aliases, DNSNames) and Ports (actual bindings)
MountsEvery volume and bind mount: Type, Source, Destination, RW
Name, Id, Image, Created, RestartCount, LogPathAs named. Name starts with /

Config is the wish, HostConfig and NetworkSettings are what Docker actually set up. Explore an unknown key with docker inspect -f '{{json .HostConfig}}' web | jq.

--format with Go templates

-f / --format takes a Go template that runs once per object. . is the object, keys are case-sensitive.

SyntaxDoesExample
{{.A.B}}Value of a nested key{{.State.Status}}
{{json .X}}Print as JSON (for maps and lists){{json .Mounts}}
{{range .List}}...{{end}}Loop; inside, . is the element{{range .Mounts}}{{.Source}} {{end}}
{{range $k, $v := .Map}}Loop over a map with key and value{{range $n, $c := .NetworkSettings.Networks}}{{$n}}{{end}}
{{index .Map "key"}}Key with dots, dashes or a variable name{{index .Config.Labels "com.docker.compose.service"}}
{{index .List 0}}List element by position{{index .RepoDigests 0}}
{{if .X}}...{{else}}...{{end}}Condition (empty, false, 0, nil are false){{if .State.Health}}{{.State.Health.Status}}{{end}}
{{eq .A "b"}}, {{ne}}, {{and}}, {{or}}, {{not}}Comparisons{{if eq .State.Status "exited"}}...{{end}}
{{join .List ", "}}Join a string list{{join .Config.Cmd " "}}
{{split .S "/"}}Split a string{{split .Name "/"}}
{{lower}}, {{upper}}, {{title}}Change case{{upper .Name}}
{{len .X}}Length{{len .Mounts}}
{{printf "%.12s" .Id}}printf formatting (here: short ID)
{{println}} or {{"\n"}}Newline, to get one line per element
{{.Name}}{{"\t"}}Tab
# Health status without failing on containers that have no healthcheck
docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' web

One-liners

WhatCommand
Status, exit code, OOM killeddocker inspect -f '{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}' web
IP on every networkdocker inspect -f '{{range $n, $c := .NetworkSettings.Networks}}{{$n}} {{$c.IPAddress}}{{println}}{{end}}' web
IP on one networkdocker inspect -f '{{(index .NetworkSettings.Networks "appnet").IPAddress}}' web
Published portsdocker inspect -f '{{range $p, $b := .NetworkSettings.Ports}}{{$p}} -> {{range $b}}{{.HostIp}}:{{.HostPort}} {{end}}{{println}}{{end}}' web
Mountsdocker inspect -f '{{range .Mounts}}{{.Type}} {{.Source}} -> {{.Destination}} rw={{.RW}}{{println}}{{end}}' web
Environment variablesdocker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' web
Entrypoint and commanddocker inspect -f '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' web
Image the container runs (ID)docker inspect -f '{{.Image}}' web
Image name it was started withdocker inspect -f '{{.Config.Image}}' web
Restart policy and restart countdocker inspect -f '{{.HostConfig.RestartPolicy.Name}} {{.RestartCount}}' web
Log driver and log filedocker inspect -f '{{.HostConfig.LogConfig.Type}} {{.LogPath}}' web
PID on the hostdocker inspect -f '{{.State.Pid}}' web
Compose project and servicedocker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}/{{index .Config.Labels "com.docker.compose.service"}}' web
All labelsdocker inspect -f '{{json .Config.Labels}}' web | jq
Last healthcheck outputdocker inspect -f '{{json .State.Health.Log}}' web | jq -r '.[-1].Output'
Image digest, OS and archdocker image inspect -f '{{index .RepoDigests 0}} {{.Os}}/{{.Architecture}}' nginx:1.27
Image default user (empty = root)docker image inspect -f '{{.Config.User}}' nginx:1.27
Containers on a networkdocker network inspect -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}' appnet
Where a volume lives on diskdocker volume inspect -f '{{.Mountpoint}}' pgdata

Name, IP and status for every running container:

docker inspect -f '{{.Name}} {{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}{{.State.Status}}' $(docker ps -q)

With jq

jq is easier for filtering across many containers and for keys you don’t know yet. The output is an array, so start with .[] or .[0]. More on jq: jq cheat sheet.

WhatCommand
Top-level keysdocker inspect web | jq '.[0] | keys'
One subtreedocker inspect web | jq '.[0].HostConfig'
Several fields as a small objectdocker inspect web | jq '.[0] | {Name, Image: .Config.Image, Status: .State.Status}'
Networks and IPsdocker inspect web | jq -r '.[0].NetworkSettings.Networks | to_entries[] | "\(.key) \(.value.IPAddress)"'
Env as KEY=value linesdocker inspect web | jq -r '.[0].Config.Env[]'
Find a key anywheredocker inspect web | jq 'paths | map(tostring) | join(".")' | grep -i log
Table of all running containersdocker inspect $(docker ps -q) | jq -r '.[] | [.Name, .Config.Image, .State.Status] | @tsv'
Diff two containers’ configdiff <(docker inspect a | jq -S '.[0].Config') <(docker inspect b | jq -S '.[0].Config')

Security audit one-liners

Run against all running containers; add -a to docker ps -q to include stopped ones.

FindsCommand
Overview: privileged, network, PID mode, added capsdocker inspect -f '{{.Name}} priv={{.HostConfig.Privileged}} net={{.HostConfig.NetworkMode}} pid={{.HostConfig.PidMode}} caps={{.HostConfig.CapAdd}}' $(docker ps -q)
Privileged containersdocker inspect $(docker ps -q) | jq -r '.[] | select(.HostConfig.Privileged) | .Name'
Docker socket mounteddocker inspect $(docker ps -q) | jq -r '.[] | select(any(.Mounts[]?; .Source == "/var/run/docker.sock")) | .Name'
Host network or host PID namespacedocker inspect $(docker ps -q) | jq -r '.[] | select(.HostConfig.NetworkMode == "host" or .HostConfig.PidMode == "host") | .Name'
Sensitive host paths mounteddocker inspect $(docker ps -q) | jq -r '.[] | .Name as $n | .Mounts[]? | select(.Source | test("^/($|etc|root|proc|sys|var/run)")) | "\($n) \(.Source)"'
Secrets in environment variablesdocker inspect $(docker ps -q) | jq -r '.[] | .Name as $n | .Config.Env[]? | select(test("PASS|SECRET|TOKEN|KEY"; "i")) | "\($n) \(.)"'
Running as root (empty user)docker inspect -f '{{.Name}} user={{.Config.User}}' $(docker ps -q)
Ports published on all interfacesdocker ps --format '{{.Names}} {{.Ports}}' | grep -E '0\.0\.0\.0|\[::\]'
Writable root filesystemdocker inspect -f '{{.Name}} readonly={{.HostConfig.ReadonlyRootfs}}' $(docker ps -q)

Environment variables of any container are readable by everyone who can run docker inspect, and they are stored in /var/lib/docker/containers/<id>/config.v2.json.

Filters and --format on list commands

docker ps, images, network ls and volume ls take --filter (repeat for AND) and --format. The fields there are different from inspect: see them with --format '{{json .}}'.

WhatCommand
Stopped containersdocker ps -a --filter status=exited
Crashed (non-zero exit)docker ps -a --filter exited=1
Unhealthydocker ps --filter health=unhealthy
From one imagedocker ps -a --filter ancestor=nginx
On one networkdocker ps --filter network=backnet
Publishing a portdocker ps --filter publish=443
Using a volumedocker ps -a --filter volume=pgdata
By label (e.g. one Compose project)docker ps --filter label=com.docker.compose.project=shop
By name (substring)docker ps --filter name=web
Custom tabledocker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
Size of each container’s writable layerdocker ps -s --format 'table {{.Names}}\t{{.Size}}'
Dangling imagesdocker images --filter dangling=true
Images by name patterndocker images --filter reference='registry.example.com/*'
Images sorted by sizedocker images --format '{{.Size}}\t{{.Repository}}:{{.Tag}}' | sort -h
Unused volumesdocker volume ls --filter dangling=true
Custom networks onlydocker network ls --filter type=custom
Raw fields of each rowdocker ps --format '{{json .}}' | jq

Gotchas

§ home
~/knubertus/home/
1,1 Top