yum安装对Docker层大小的影响

问题描述

在没有IT背景的情况下,我已经使用Docker一段时间了。

现在,我正在努力了解如何通过优化Dockerfile来最小化Docker映像的大小。从这个意义上讲,我遇到了一个最小的可复制案例,我不理解。如果有人可以分享他的想法或提供解释,我将感到非常高兴。

我从一个官方centos:7图像开始(7e6257c9f8d8; 203MB)。然后,我准备以下Dockerfile:

FROM centos:7
RUN yum -y install nano && yum -y clean all && rm -fr /var/cache
RUN yum -y install which && yum -y clean all && rm -fr /var/cache
RUN yum -y install which && yum -y clean all && rm -fr /var/cache

该想法是安装任何轻量级软件包并评估对图像大小的影响。为此,我先安装 nano ,然后在另一个标签中安装哪个。我添加了额外的尝试来安装哪个(这表明没有事可做)。而且,我添加 yum clean all 语句以清理yum缓存,以防万一(即使我只是检查了删除此命令后实验结果是否不变),还是删除了/ var /缓存目录(在基本映像中为空)。

结果如下:

IMAGE               CREATED             CREATED BY                                      SIZE  
6a14537d3460        7 seconds ago       /bin/sh -c yum -y install which && yum -y cl…   23.9MB
7d924cbdf819        22 seconds ago      /bin/sh -c yum -y install which && yum -y cl…   24.2MB
2b5b04d37a64        42 seconds ago      /bin/sh -c yum -y install nano && yum -y cle…   24.6MB

的安装大小为75k, nano 的安装大小为1.6M。我没有发现任何其他已安装的依赖项。

问题是:为什么即使实际上没有安装任何软件包,这些安装命令中的每个命令也会将最终映像增加〜24MB层?

提前感谢社区:)

解决方法

每条RUN指令都会创建一个新的docker层。

Docker本身还不够聪明,无法检测到该指令实际上什么也没做。

它会在结果图像中忠实地存储新的docker层。

这就是为什么您需要尽量减少docker指令的数量。

根据您的情况,您只能使用一个RUN指导:

RUN yum -y install nano which && yum -y clean all && rm -fr /var/cache 

更新

让我们做个实验:

FROM centos
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which
RUN yum -y install which

10条RUN指令,其中9条“什么都不做”。

让我们构建并寻找中间图像

$ docker build .
...
$ docker images -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              fbd86aedc782        5 seconds ago       263MB
<none>              <none>              ca70a4bbe722        7 seconds ago       261MB
<none>              <none>              bd11e0ab02fb        9 seconds ago       259MB
<none>              <none>              68c20ddfcaad        11 seconds ago      257MB
<none>              <none>              314a6501ad23        13 seconds ago      255MB
<none>              <none>              42a62294a5e7        16 seconds ago      253MB
<none>              <none>              16fad39b9c27        18 seconds ago      251MB
<none>              <none>              6769fe69c9e1        19 seconds ago      249MB
<none>              <none>              49cef483e732        21 seconds ago      248MB
<none>              <none>              c4c92c39f2a4        23 seconds ago      246MB
centos              latest              0d120b6ccaa8        3 weeks ago         215MB

我看到每个下一个用于“不执行任何操作”的docker图像层都会增加〜2Mb。 (我不知道OP问题中的〜24 Mb)

更新2

根据emix的建议:使用dive,我立即发现/var/rpm/var/log的每一层都被更改的文件