将 ARG 放在 Dockerfile 顶部会阻止层重用吗? [英] Does putting ARG at top of Dockerfile prevent layer re-use?
问题描述
如果在 Dockerfile 顶部声明的 ARG 发生更改,但其值仅用于 Dockerfile 末尾附近的 RUN 命令,Docker 是从头开始重建整个映像还是能够重新使用相关 RUN 命令之前的中间图像?
If an ARG that is declared at the top of a Dockerfile gets changed, but its value is only used for a RUN command near the end of the Dockerfile, does Docker rebuild the whole image from scratch or is it able to re-use the intermediate image from right before the relevant RUN command?
为了更好地利用分层,我应该将我的 ARG 声明放在 Dockerfile 的顶部,还是就在使用它们的部分之前?
To better utilize layering, should I place my ARG declarations at the top of the Dockerfile, or just before the section that uses them?
我想我的部分问题是 ARG 指令是否会生成中间层.
I guess part of my question is whether or not an ARG directive generates an intermediate layer.
推荐答案
为了比接受的响应更精确,在 ARG
声明之后,并非所有行都缓存无效.只有那些使用 ARG
值和 RUN
的.docker文档的详细信息:
To be more precise than the accepted response, not all lines are cache invalidated after an ARG
declaration. Only those that use ARG
values and RUN
s. The docker documentation the details:
对构建缓存的影响
ARG
变量不会像 ENV
变量那样持久化到构建的图像中.但是,ARG
变量确实会以类似的方式影响构建缓存.如果 Dockerfile 定义了一个 ARG 变量,其值与以前的构建不同,那么在第一次使用时会发生缓存未命中",而不是定义.特别是,ARG
指令之后的所有 RUN
指令都隐式使用 ARG
变量(作为环境变量),因此可能导致缓存未命中.所有预定义的 ARG
变量都免于缓存,除非 Dockerfile 中有匹配的 ARG
语句.
ARG
variables are not persisted into the built image as ENV
variables are. However, ARG
variables do impact the build cache in similar ways. If a Dockerfile defines an ARG variable whose value is different from a previous build, then a "cache miss" occurs upon its first usage, not its definition. In particular, all RUN
instructions following an ARG
instruction use the ARG
variable implicitly (as an environment variable), thus can cause a cache miss. All predefined ARG
variables are exempt from caching unless there is a matching ARG
statement in the Dockerfile.
- https://docs.docker.com/engine/reference/builder/#impact-on-build-caching
- https://github.com/moby/moby/issues/18017
- https://github.com/moby/moby/pull/18161
- 在这里运行解释:https://github.com/moby/moby/pull/21885
您必须将您的 ARG
s 移动到不需要参数的 RUN
s 下,以保持层缓存优化.
You'll have to move your ARG
s under the RUN
s that would not need the argument in order to keep layer cache optimized.
更多信息:
这篇关于将 ARG 放在 Dockerfile 顶部会阻止层重用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!