本文介绍了在Dockerfile中的单个RUN指令中指定多个UNIX命令的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到许多 Dockerfile 试图通过单个< UNIX 命令在 RUN 指令。那么,有什么原因吗?

I have notice that many Dockerfiles try to minimize the number of instructions by several UNIX commands in a single RUN instruction. So is there any reason?


  • 而且两个 Dockerfile s以下?

  • And also is there any difference in outcome between the two Dockerfiles below?

Dockerfile1

FROM ubuntu 
MAINTAINER [email protected] 

RUN apt-get update 
RUN apt-get install –y nginx 
CMD ["echo", "Image created"] 

Dockerfile2

FROM ubuntu 
MAINTAINER [email protected] 

RUN apt-get update && apt-get install –y nginx 
CMD ["echo", "Image created"] 


推荐答案

粗略地说,Docker映像包含一些元数据&一层数组,并通过添加一个容器层(读写)在这些层上构建运行中的容器,此时基础映像中的层是只读的。

Roughly speaking, a Docker image contains some metadata & an array of layers, and a running container is built upon these layers by adding a container layer (read-and-write), the layers from the underlying image being read-only at that point.

可以根据配置的驱动程序以不同方式将这些层存储在磁盘中。例如,以下来自Docker官方文档的图像说明了

These layers can be stored in the disk in different ways depending on the configured driver. For example, the following image taken from the official Docker documentation illustrates the way the files changed in these different layers are taken into account with the OverlayFS storage driver:

接下来,Dockerfile指令 RUN COPY ADD 创建层,Docker网站上提到的最佳实践特别建议将连续的 RUN 命令合并到单个 RUN 命令,以减少层数,从而减小最终图像的大小

Next, the Dockerfile instructions RUN, COPY, and ADD create layers, and the best practices mentioned on the Docker website specifically recommend to merge consecutive RUN commands in a single RUN command, to reduce the number of layers, and thereby reduce the size of the final image:

另请参见:

此外,在您的示例中:

RUN apt-get update -y -q
RUN apt-get install -y nginx

如果您执行 docker build -t your-image-name。 放在 Dockerfile 上,然后编辑 Dockerfile 一会儿,在 nginx ,然后再次执行 docker build -t your-image-name。,由于Docker缓存机制, apt-get update -y -q 不会再次执行,因此APT缓存将过时。因此,这是合并两个 RUN 命令的另一个好处。

if you do docker build -t your-image-name . on this Dockerfile, then edit the Dockerfile after a while, add another package beyond nginx, then do again docker build -t your-image-name ., due to the Docker cache mechanism, the apt-get update -y -q won't be executed again, so the APT cache will be obsolete. So this is another upside for merging the two RUN commands.

这篇关于在Dockerfile中的单个RUN指令中指定多个UNIX命令的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 19:05