如何在持续集成中删除旧docker图像以节省磁盘空间

在连续集成环境中构builddocker映像时,您很快就会耗尽磁盘空间并需要删除旧映像。 但是,您不能删除所有旧图像,包括中间图像,因为这会破坏caching。

如何避免构build代理中的磁盘空间不足,而又不会破坏caching?

我的解决scheme是在构build新图像之后删除以前版本的图像。 这可以确保caching的图像可以加速构build,但避免旧图像堆积和吃掉磁盘空间。 这种方法依赖于具有唯一标签的图像的每个版本。

这是我的脚本( 在这里主旨):

#!/usr/bin/env bash usage(){ # ============================================================ echo This script removes all images of the same repository and echo older than the provided image from the docker instance. echo echo This cleans up older images, but retains layers from the echo provided image, which makes them available for caching. echo echo Usage: echo echo '$ ./delete-images-before.sh <image-name>:<tag>' exit 1 # ============================================================ } [[ $# -ne 1 ]] && usage IMAGE=$(echo $1 | awk -F: '{ print $1 }') TAG=$(echo $1 | awk -F: '{ print $2 }') FOUND=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep ${IMAGE}:${TAG}) if ! [[ ${FOUND} ]] then echo The image ${IMAGE}:${TAG} does not exist exit 2 fi docker images --filter before=${IMAGE}:${TAG} \ | grep ${IMAGE} \ | awk '{ print $3 }' \ | xargs --no-run-if-empty \ docker --log-level=warn rmi --force || true 

我们用来处理这个问题的工具是docker custodian(dcgc)。

build议保留一张你想要保留的图像清单,永远不要清理,并把它传递给--exclude-image (如果你使用puppet或其他资源pipe理系统,写一个文件到磁盘,包含图像模式,而不是使用--exclude-image-file