在持续集成环境中构建 docker 映像时,磁盘空间很快就会耗尽,需要删除旧映像。但是,您无法删除所有旧图像,包括中间图像,因为这会中断缓存。
如何在不中断缓存的情况下避免生成代理上的磁盘空间不足?
我的解决方案是在构建新版本后删除以前版本的映像。这可确保缓存的映像可用于加快构建速度,但避免旧映像堆积并占用磁盘空间。此方法依赖于具有唯一标记的每个映像版本。
这是我的脚本(要点在这里(:
#!/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(。
建议保留一个要保留的映像列表,并且永远不要清理并将其传递给--exclude-image
(如果您使用的是puppet
或其他资源管理系统,则使用包含映像模式的文件到磁盘并使用--exclude-image-file
可能更有用(