简体   繁体   English

我可以在 Dockerfile 中结合 COPY 指令来最小化图像层的数量吗?

[英]Can I combine COPY directives in Dockerfile to minimize number of image layers?

I saw this post , explaining how it is better to have a combined RUN directive instead of multiple RUN s, (ie RUN a && b && c is better than RUN a; RUN b; RUN c; ).我看到这篇文章,解释了如何使用组合RUN指令而不是多个RUN指令更好(即RUN a && b && c优于RUN a; RUN b; RUN c; )。

I want to do the same for the COPY directive.我想对COPY指令做同样的事情。

In case of the same dst, I can just do COPY /src/a/ /src/b/* /src/*/c dst/ .如果 dst 相同,我可以COPY /src/a/ /src/b/* /src/*/c dst/ However, when having multiple destinations, I can't do it.但是,当有多个目的地时,我做不到。

I tried COPY src/a dst/a && src/b dst/b but it failed:我试过COPY src/a dst/a && src/b dst/b但它失败了:

/var/lib/docker/tmp/docker-builder.../&&: no such file or directory

meaning the && wasn't parsed correctly.这意味着&&没有被正确解析。

Is there a way to have a concise COPY directive?有没有办法有一个简洁的COPY指令?

No, you can't have multiple destinations per COPY directive.不,每个COPY指令不能有多个目的地。 If you want to use just a single COPY then, if possible, build your directory structure outside the container so that it matches the expected result inside of the container and just copy the whole structure.如果您只想使用一个COPY ,那么如果可能的话,在容器外部构建您的目录结构,以便它与容器内部的预期结果相匹配,然后只复制整个结构。

/var/lib/docker/tmp/docker-builder.../&&: no such file or directory /var/lib/docker/tmp/docker-builder.../&&: 没有那个文件或目录

meaning the && wasn't parsed correctly.这意味着 && 没有被正确解析。

&& was parsed correctly. &&被正确解析。 It was parsed as a filename because that is how the underlying function that executes COPY command is implemented.它被解析为文件名,因为这是执行COPY命令的底层 function 的实现方式。

COPY [--chown=<user>:<group>] <src>... <dest>

Also, note that one of the reasons for having just one (or just a small bunch) of RUN directives is that each of these is executed in its own intermediate container which is immediately removed once the particular RUN directive is executed which obviously produces an additional overhead that can be avoided by simply chaining the commands.另外,请注意,只有一个(或一小群) RUN指令的原因之一是这些指令中的每一个都在其自己的中间容器中执行,一旦执行特定的RUN指令,它就会立即被删除,这显然会产生额外的可以通过简单地链接命令来避免的开销。

This is not the case with COPY though.但是COPY不是这种情况。 Even if you have 100s COPY directives, all of these are executed without creating and removing any intermediate containers.即使您有 100 条COPY指令,所有这些指令也会在不创建和删除任何中间容器的情况下执行。 Personally, I am not worried about having additional COPY directive if it makes the Dockerfile more readable.就我个人而言,如果它使 Dockerfile 更具可读性,我并不担心有额外的COPY指令。 This doesn't affect build speed and/or size of the container in any significant way.这不会以任何显着方式影响容器的构建速度和/或大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM