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

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

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


当前回答

Docker系统修剪-a

(系统会要求您确认命令。使用-f强制运行,如果你知道你在做什么。)

其他回答

下面是一个清理Docker映像并回收空间的脚本。

#!/bin/bash -x
## Removing stopped container
docker ps -a | grep Exited | awk '{print $1}' | xargs docker rm

## If you do not want to remove all container you can have filter for days and weeks old like below
#docker ps -a | grep Exited | grep "days ago" | awk '{print $1}' | xargs docker rm
#docker ps -a | grep Exited | grep "weeks ago" | awk '{print $1}' | xargs docker rm

## Removing Dangling images
## There are the layers images which are being created during building a Docker image. This is a great way to recover the spaces used by old and unused layers.

docker rmi $(docker images -f "dangling=true" -q)

## Removing images of perticular pattern For example
## Here I am removing images which has a SNAPSHOT with it.

docker rmi $(docker images | grep SNAPSHOT | awk '{print $3}')

## Removing weeks old images

docker images | grep "weeks ago" | awk '{print $3}' | xargs docker rmi

## Similarly you can remove days, months old images too.

原始的脚本

https://github.com/vishalvsh1/docker-image-cleanup

通常Docker将所有与图像构建和图层相关的临时文件保存在

/var/lib/docker

该路径是系统的本地路径,通常位于根分区“/”。

您可以挂载一个更大的磁盘空间,并将/var/lib/docker的内容移动到新的挂载位置,并进行符号链接。

这样,即使Docker映像占用空间,也不会影响您的系统,因为它将使用其他一些挂载位置。

原文章:管理本地磁盘上的Docker映像

我最近写了一个脚本在我的服务器上解决这个问题:

#!/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"}' \
))

# Get all the images currently available
ALL_IMAGES=($( \
    docker images --format '{{.Repository}}:{{.Tag}}' | \
    sort -u \
))

# Remove the unused images
for i in "${ALL_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

如果您希望自动/定期清理退出的容器,并删除运行中的容器不使用的映像和卷,您可以下载映像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 rm $(docker ps -faq)
docker rmi $(docker ps -faq)

- f力

——所有

-q模式

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

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