docker清理10天前历史缓存中间镜像

683 阅读2分钟

docker清理10天前历史缓存中间镜像

docker images -f "dangling=true" '--format={{.Tag}} {{.ID}} {{.CreatedAt}}' | awk '{CS=mktime(sprintf("%s %s %s 00 00 00",substr($3,0,4),substr($3,6,2),substr($3,9,2)));ID=$2;NS=systime();DT=NS-10*86400;if(DT > CS){print ID}}' | xargs -r docker rmi -f

什么是中间镜像?

中间镜像的产生

在使用命令 build 命令构建镜像时,比如:

docker build -t demo4docker .

构建完成后,查看镜像:

docker images -a
----------------
REPOSITORY      TAG         IMAGE ID       CREATED         SIZE
demo4docker     latest      09dc6a85ec83   6 days ago      776MB
<none>          <none>      912c358695d4   6 days ago      776MB
<none>          <none>      affb7d9f6529   6 days ago      709MB
<none>          <none>      b58ee21ac8b6   6 days ago      643MB

发现出现了几个没有既没有 REPOSITORY 也没有 TAG 的镜像,这些就是中间镜像intermediate images)。

有效none镜像 和 无效none镜像

有效none镜像:

Docker 文件系统是由很多 layers 组成的,每个 layer 之间有父子关系,所有的 docker 文件系统层默认都存储在 /var/lib/docker/graph 目录下,docker 称之为图层数据库。

所以,这些 <none>:<none> 镜像是镜像的父层,必须存在的,并且不会造成硬盘空间占用问题。

无效 none 镜像

而 docker 还存在另一种没有被使用到的并且不会关联任何镜像的 <none>:<none> 镜像,这些镜像被称之为 dangling images,这种类型的镜像会造成磁盘空间占用问题。

使用 docker rmi 命令删除

执行以为删除命令:

docker rmi $(docker images -a | grep "<none>" | awk '$1=="<none>" {print $3}')

命令解释:

该命令先通过 docker images -a 列出所有镜像(包括中间镜像);

然后通过 grep 过滤出 REPOSITORY 或 TAG 为 的镜像列表;

接着再通过 awk 命令提出出这些镜像的镜像 ID;

最后再交给 rmi 命令批量删除镜像。

执行过程中可能会提示如下错误:

Error response from daemon: conflict: unable to delete 912c358695d4 (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete affb7d9f6529 (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete b58ee21ac8b6 (cannot be forced) - image has dependent child images

因为这些镜像是有效的 none 镜像,存在依赖关系,要想删除就需要先清除掉引用这些镜像的子镜像,但不建议删除这些有效的 none 镜像

但我们可以使用以下命令删除无效的 none 镜像:

# 查看是否有无效的 none 镜像
docker images -f "dangling=true"

# 如果有的话就执行以下删除命令
docker rmi $(docker images -f "dangling=true" -q)

构建镜像过程中强制删除中间镜像

可以通过再构建镜像的命令中添加 --force-rm 参数来删除镜像构建过程中生成的中间镜像:

docker build --force-rm -t myimage .

不产生中间镜像,那么在docker build时,无法利用之前的缓存来加快构建速度,所以是要保留中间镜像的,但是我们还需要一种机制,保留一定天数的中间镜像,避免磁盘撑满了。

  • 第一种试了无效
docker builder prune --filter  'until=240h' -f
  • 第二种有效删除10天前的
docker images -f "dangling=true" '--format={{.Tag}} {{.ID}} {{.CreatedAt}}' | awk '{CS=mktime(sprintf("%s %s %s 00 00 00",substr($3,0,4),substr($3,6,2),substr($3,9,2)));ID=$2;NS=systime();DT=NS-10*86400;if(DT > CS){print ID}}' | xargs -r docker rmi -f

第二种语法分解说明

1、列出所有none的镜像

docker images -f "dangling=true"

image.png

2、format格式化获取创建时间,不用相对时间

docker images -f "dangling=true" '--format={{.Tag}} {{.ID}} {{.CreatedAt}}' 

image.png

3、awk时间格式化为时间戳和判定是否10天以上

docker images -f "dangling=true" '--format={{.Tag}} {{.ID}} {{.CreatedAt}}' | awk '{CS=mktime(sprintf("%s %s %s 00 00 00",substr($3,0,4),substr($3,6,2),substr($3,9,2)));ID=$2;NS=systime();DT=NS-10*86400;if(DT > CS){print ID}}'

4、最后xargs循环删除镜像