gpt4 book ai didi

docker - 如何列出图像及其容器

转载 作者:行者123 更新时间:2023-12-02 05:47:57 27 4
gpt4 key购买 nike

我正在删除悬空的 docker 镜像。

在删除这些图像之前,我想看看是否有任何容器,它们是这些悬空图像的实例。

如果是这样,我想记录它们并中止删除。

到目前为止我还没有找到任何相关命令。

我的解决方案是获取所有容器docker ps -a和所有悬挂图像docker images -aqf dangling=true并比较repo + tag code> 来自图像,image 来自容器。

我正在使用docker1.12

最佳答案

How to list images and their containers?

您可以编辑--format以满足您的需求:

docker ps -a --format="container:{{.ID}} image:{{.Image}}"

How to delete dangling images?

此命令旨在清理悬空图像,而不触及容器正在使用的图像:

$ docker image prune

WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y
<小时/>

但是如果您的 docker 版本中没有该命令,您可以尝试以下操作。

如果图像悬空,您应该在 docker ps 的 IMAGE 列中看到一个哈希值。这不应该是一个常见的情况,很难。

这会通过运行/停止的容器打印使用的图像:

docker ps -a --format="{{.Image}}"

这列出了您的悬挂图像:

docker images -qf "dangling=true"

谨慎服用:

#!/bin/bash

# Remove all the dangling images
DANGLING_IMAGES=$(docker images -qf "dangling=true")
if [[ -n $DANGLING_IMAGES ]]; then
docker rmi "$DANGLING_IMAGES"
fi

# Get all the images currently in use
USED_IMAGES=($( \
docker ps -a --format '{{.Image}}' | \
sort -u | \
uniq | \
awk -F ':' '$2{print $1":"$2}!$2{print $1":latest"}' \
))

# Remove the unused images
for i in "${DANGLING_IMAGES[@]}"; do
UNUSED=true
for j in "${USED_IMAGES[@]}"; do
if [[ "$i" == "$j" ]]; then
UNUSED=false
fi
done
if [[ "$UNUSED" == true ]]; then
docker rmi "$i"
fi
done

关于docker - 如何列出图像及其容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com