在长时间运行Docker时,系统中存在大量的镜像。如何一次安全地删除所有未使用的Docker映像以释放存储空间?

另外,我还想删除几个月前拉的图片,这些图片有正确的TAG。

因此,我并不是只要求删除未标记的图像。我正在寻找一种方法来删除一般不使用的图像,其中包括未标记和其他图像,如几个月前拉正确的TAG。


当前回答

要删除超过一个月的旧标记图像:

$ docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' \
    | grep ' months' | awk '{ print $1 }' \
    | xargs --no-run-if-empty docker rmi

注意,它将无法删除容器使用的图像,在存储库中引用,有依赖的子图像…这可能是你想要的。否则只需添加-f标志。

/etc/cron.示例每日/ docker-gc脚本:

#!/bin/sh -e

# Delete all stopped containers (including data-only containers).
docker ps -a -q --no-trunc --filter "status=exited" | xargs --no-run-if-empty docker rm -v

# Delete all tagged images more than a month old
# (will fail to remove images still used).
docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' | grep ' months' | awk '{ print $1 }' | xargs --no-run-if-empty docker rmi || true

# Delete all 'untagged/dangling' (<none>) images
# Those are used for Docker caching mechanism.
docker images -q --no-trunc --filter dangling=true | xargs --no-run-if-empty docker rmi

# Delete all dangling volumes.
docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm

其他回答

如果你想删除X个月前的图片,你可以尝试下面的例子,删除三个月前创建的图片:

three_months_old_images=`docker images | grep -vi "<none>" | tr -s ' ' | cut -d" " -f3,4,5,6 | grep "3 months ago" | cut -d" " -f1`
docker rmi $three_months_old_images

@VonC已经给出了一个非常好的答案,但为了完整起见,这里有一个我一直在使用的小脚本——如果你有一些差事,它也会破坏任何Docker进程:

#!/bin/bash

imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
   echo docker rmi ${imgs}
   docker rmi ${imgs}
else
   echo "No images to remove"
fi

procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
   echo docker rm ${procs}
   docker rm ${procs}
else
   echo "No processes to purge"
fi

根据文档,下面的命令将删除超过48小时的图像。

$ docker image prune --all --filter until=48h

如果您希望自动/定期清理退出的容器,并删除运行中的容器不使用的映像和卷,您可以下载映像meltwater/docker-cleanup。

运行:

docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw  -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest

默认每30分钟运行一次。但是,您可以使用该标志以秒为单位设置延迟时间(DELAY_TIME=1800选项)。

详情:https://github.com/meltwater/docker-cleanup/blob/master/README.md

假设你有Docker 1.13或更高版本,你可以只使用修剪命令。对于你的问题,特别是关于删除旧图像,你想要第一个。

# Remove unused images
docker image prune

# Remove stopped containers.
docker container prune

# Remove unused volumes
docker volume prune

# Remove unused networks
docker network prune

# Command to run all prunes:
docker system prune

我建议不要习惯使用docker系统的prune命令。我认为用户会不小心删除他们不想删除的内容。就我个人而言,我将主要使用docker映像修剪和docker容器修剪命令。