Docker RUN命令

在这篇关于Docker的CMD vs. RUNENTRYPOINT的文章中,我感到困惑。

请注意, apt-get updateapt-get install是在单个RUN指令中执行的。 这样做是为了确保安装最新的软件包。 如果apt-get install在一个单独的RUN指令中,那么它将重新使用apt-get update添加的一个图层,这个图层可能早就被创build了。

给出的代码是:

 RUN apt-get update && apt-get install -y \ bzr \ cvs \ git \ mercurial \ subversion 

我真的不明白他们在同一行上apt-get install的解释。 不会apt-get update完成,然后apt-get install...将继续,如果他们在不同的线路上? 这篇文章使得它听起来像apt-get install...不会看到任何apt-get update在独立行上产生的效果。

参考是caching图层。 无论何时,对相同的上一层运行相同的命令,Docker都会尝试重新使用该命令的caching层。

所以,如果你从现在开始的几个月内将其他软件包添加到你的列表中,并重新运行docker build ,如果你做了两个独立的RUN命令, apt-get update层将从caching中被重用,并且你有一个3个月的caching在你的形象。 在第二次运行时在新的apt-get install命令中安装软件包的尝试将会失败,因为旧软件包不在软件包存储库中。

通过将它作为一个单独的RUN命令,它是文件系统caching中的一个单独的层,因此它从现在开始重新生成重build月份的更新,并在当前位于软件包存储库中的软件包上执行安装。


编辑:似乎这还不清楚,这是一个示例如何出错的情况:

使用下面的Dockerfile:

 FROM debian:latest RUN apt-get update RUN apt-get install -y \ bzr \ cvs \ git \ mercurial \ subversion 

当我运行docker built -t my-app:latest . 它输出一个很长的列表,结束于:

 Processing triggers for libc-bin (2.19-18+deb8u4) ... Processing triggers for systemd (215-17+deb8u4) ... Processing triggers for ca-certificates (20141019+deb8u1) ... Updating certificates in /etc/ssl/certs... 174 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d....done. Processing triggers for sgml-base (1.26+nmu4) ... ---> 922e466ac74b Removing intermediate container 227318b98393 Successfully built 922e466ac74b 

现在,如果我更改这个文件来添加解压缩到包列表,并假设它几个月后, apt-get update现在包含陈旧的数据:

 FROM debian:latest RUN apt-get update RUN apt-get install -y \ bzr \ cvs \ git \ mercurial \ subversion \ unzip 

如果我现在运行它,它将工作:

 Step 1 : FROM debian:latest ---> 1b088884749b Step 2 : RUN apt-get update ---> Using cache ---> 81ca47119e38 Step 3 : RUN apt-get install -y bzr cvs git mercurial subversion unzip ---> Running in 87cb8380ec90 Reading package lists... Building dependency tree... The following extra packages will be installed: ca-certificates dbus file fontconfig fontconfig-config fonts-dejavu-core gir1.2-glib-2.0 git-man gnupg-agent gnupg2 hicolor-icon-theme .... Processing triggers for libc-bin (2.19-18+deb8u4) ... Processing triggers for systemd (215-17+deb8u4) ... Processing triggers for ca-certificates (20141019+deb8u1) ... Updating certificates in /etc/ssl/certs... 174 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d....done. Processing triggers for sgml-base (1.26+nmu4) ... ---> d6d1135481d3 Removing intermediate container 87cb8380ec90 Successfully built d6d1135481d3 

但是,如果你看看上面的输出, apt-get update显示:

  ---> Using cache 

这意味着它没有运行更新,它只是重用了以前运行这个步骤的旧图层。 只有5分钟的时间,这是没有问题的。 但是,几个月前,你会看到错误。

正如Docker提到的,修复程序是运行更新并作为相同的运行步骤进行安装,这样当安装caching失效时,更新也会重新运行。