我正在尝试使用docker ps和json格式命令生成一个类似于这样的输出
{"Names":"name"}
docker ps --format '{{json .Names}}'
输出不带标签的CCD_ 1。
docker ps --format '{{json .}}'
提供了所有带有标签的容器信息,但我不想要所有信息。
最好基于下面的所有占位符名称,我希望有一个像下面这样的输出,其中包含我按照选择的顺序选择的字段:
{"ID":"Container ID", "Image":"Image ID", "Names":"name"}
Placeholder Description
.ID Container ID
.Image Image ID
.Command Quoted command
.CreatedAt Time when the container was created.
.RunningFor Elapsed time since the container was started.
.Ports Exposed ports.
.Status Container status.
.Size Container disk size.
.Names Container names.
.Labels All labels assigned to the container.
.Label Value of a specific label for this container. For example '{{.Label "com.docker.swarm.cpu"}}'
.Mounts Names of the volumes mounted in this container.
.Networks Names of the networks attached to this container.
您可以使用以下格式:
docker ps --format '{"ID":"{{ .ID }}", "Image": "{{ .Image }}", "Names":"{{ .Names }}"}'
它输出:
{"ID":"ed3c992b7472", "Image": "alpine:3.9", "Names":"wizardly_buck"}
@mcuenez作为评论告诉我们。在我看来,他的建议比@Mickael B.的要好,因为它更通用,你不必写一个很长的命令来获取所有数据。
docker ps --all --no-trunc --format='{{json .}}'
并且为了实现输出,可以使用jq
。
docker ps --all --no-trunc --format="{{json . }}" | jq --tab .
输出将类似于这个
{
"Command": "zsh",
"CreatedAt": "2023-02-22 23:40:37 +0100 CET",
"ID": "b2163d5d7229",
"Image": "local-image-with-zsh",
"Labels": "org.opencontainers.image.ref.name=ubuntu,org.opencontainers.image.version=22.04",
"LocalVolumes": "0",
"Mounts": "",
"Names": "nervous_einstein",
"Networks": "bridge",
"Ports": "",
"RunningFor": "14 minutes ago",
"Size": "215kB (virtual 1.22GB)",
"State": "running",
"Status": "Up 14 minutes"
}
{
"Command": "bash",
"CreatedAt": "2023-02-22 23:39:22 +0100 CET",
"ID": "1281e43c27a4",
"Image": "ghcr.io/example-user/remote-image-with-bash",
"Labels": "org.opencontainers.image.ref.name=ubuntu,org.opencontainers.image.version=22.04",
"LocalVolumes": "0",
"Mounts": "",
"Names": "hardcore_cerf",
"Networks": "bridge",
"Ports": "",
"RunningFor": "15 minutes ago",
"Size": "216kB (virtual 1.22GB)",
"State": "running",
"Status": "Up 15 minutes"
}
使用jq
,您甚至可以从带有-s
标志的单个条目中创建一个有效的json。
[
{
"Command": "zsh",
"CreatedAt": "2023-02-22 23:40:37 +0100 CET",
"ID": "b2163d5d7229",
"Image": "local-image-with-zsh",
"Labels": "org.opencontainers.image.ref.name=ubuntu,org.opencontainers.image.version=22.04",
"LocalVolumes": "0",
"Mounts": "",
"Names": "nervous_einstein",
"Networks": "bridge",
"Ports": "",
"RunningFor": "20 minutes ago",
"Size": "215kB (virtual 1.22GB)",
"State": "running",
"Status": "Up 20 minutes"
},
{
"Command": "bash",
"CreatedAt": "2023-02-22 23:39:22 +0100 CET",
"ID": "1281e43c27a4",
"Image": "ghcr.io/example-user/remote-image-with-bash",
"Labels": "org.opencontainers.image.ref.name=ubuntu,org.opencontainers.image.version=22.04",
"LocalVolumes": "0",
"Mounts": "",
"Names": "hardcore_cerf",
"Networks": "bridge",
"Ports": "",
"RunningFor": "21 minutes ago",
"Size": "216kB (virtual 1.22GB)",
"State": "running",
"Status": "Up 21 minutes"
}
]