docker inspect 输出又长又杂,怎么只取需要的?哪些字段是容器的、哪些是镜像的?SizeRw 为什么不显示?这篇逐项实测结构和常用的 --format 写法。
容器 inspect 的顶层键(24 个):AppArmorProfile Args Config Created Driver ExecIDs HostConfig HostnamePath HostsPath Id Image ImageManifestDescriptor LogPath MountLabel Mounts Name NetworkSettings Path Platform ProcessLabel ResolvConfPath RestartCount State Storage State 下有 11 个键 Config 下有 17 个键 HostConfig 下有 63 个键 NetworkSettings 下有 4 个键 State 的键:Dead Error ExitCode FinishedAt OOMKilled Paused Pid Restarting Running StartedAt Status 镜像 inspect 的顶层键(14 个):Architecture Comment Config Created Descriptor Id Identity Metadata Os RepoDigests RepoTags RootFS Size Variant
容器对象有 Config(创建时的配置)、HostConfig(63 项运行时配置)、State(运行状态)、NetworkSettings、Mounts 等;镜像对象有 Config、RootFS、Size、RepoTags 等。同一个字段名(如 Config)在两者里含义不同。
进程 PID:{{.State.Pid}} → 52638
环境变量:{{json .Config.Env}} → ["MODE=demo","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"]
标签:{{json .Config.Labels}} → {"bwlab":"1","role":"web"}
挂载:{{range .Mounts}}{{.Type}}:{{.Name}}->{{.Destination}} {{end}} → volume:<名>v->/data
端口映射:{{json .NetworkSettings.Ports}} → {"80/tcp":[{"HostIp":"127.0.0.1","HostPort":"55001"}]}
取端口 80/tcp 的第一个宿主机端口:{{(index (index .NetworkSettings.Ports "80/tcp") 0).HostPort}} → 55001
内存上限:{{.HostConfig.Memory}} → 67108864
截取 ID 前 12 位:{{printf "%.12s" .Id}} → c0a674ff39c9
IP(bridge):{{(index .NetworkSettings.Networks "bridge").IPAddress}} → 172.17.0.2
不存在的字段:退出码 1;template parsing error: template: :1:2: executing "" at <.NoSuchField>: map has no entry for key "NoSuchField"--format 用 Go 模板:json 输出子树的 JSON,index 按键取值(端口映射、网络都用得上),range 遍历,printf 格式化。模板里引用了不存在的键会报错而不是输出空。
SizeRw:写 10 MiB 前 8192,写后 10493952;SizeRootFs:9515008 → 20000768 不带 -s 时有 SizeRw 字段吗?False
-s 让 inspect 多算 SizeRw(可写层)和 SizeRootFs,会多花一点时间;默认不带这两个字段。
容器和镜像都叫 bwlab-c71-dup(镜像是 docker tag 出来的):docker inspect bwlab-c71-dup 返回 1 个对象,它是容器 --type image:[alpine:3.20 bwlab-c71-dup:latest];--type container:/bwlab-c71-dup 对象不存在:退出码 1;输出 error: no such object: no-such-thing
容器名和镜像名相同时,inspect 默认先匹配容器,用 --type image 或 --type container 消除歧义。