问题描述
我正在使用Docker 18.05.0~ce~3-0~ubuntu
,我想将构建参数传递给FROM和Dockerfile中的其他行.您希望以下代码可以正常工作:
I'm using Docker 18.05.0~ce~3-0~ubuntu
and I'd like to pass a build argument to the FROM as well as other lines in my Dockerfile. You would expect the below to work:
ARG FROM_IMAGE=ubuntu:bionic
FROM $FROM_IMAGE
COPY sources_list/$FROM_IMAGE /etc/apt/sources.list
它适用于第二行(FROM
),但其行为就像未在COPY
行中设置一样:
It works for the second line (FROM
), but it behaves like it is unset in the COPY
line:
如果添加另一个单独的生成arg,则它适用于同一COPY
行:
If add another, separate build arg, it works for the same COPY
line:
ARG FROM_IMAGE=ubuntu:bionic
FROM $FROM_IMAGE
ARG SOURCES_LIST_FILE
COPY sources_list/${SOURCES_LIST_FILE} /etc/apt/sources.list
为什么在FROM
行上和之后不能两次使用FROM_IMAGE
build arg?我找不到任何记录在案的这种限制.
Why can't I use the FROM_IMAGE
build arg twice, on and after a FROM
line? I fail to find any documented restriction of this sort.
推荐答案
取决于将ARG与FROM行相关的放置位置,确实存在实际差异:
There is a real difference depending on where you put ARG related to FROM line:
- 第一个FROM之前的任何ARG都可以在任何FROM行中使用
- 在构建阶段(在FROM之后)内的任何ARG都可以在该构建阶段使用
这与构建阶段的机制有关,可以在此处找到一些实际行为参考: https://github.com/docker/cli/pull/333 ,以及有关为何文档和构建机制在ARG使用上有些混乱的讨论在这里: https://github.com/moby/moby/issues/34129
This is related to build stages mechanics and some reference of actual behavior can be found here: https://github.com/docker/cli/pull/333, and a discussion on why documentation and build mechanics is a bit confusing on ARG usage is here: https://github.com/moby/moby/issues/34129
这篇关于为什么在FROM中之后在Dockerfile中不能再次使用build arg?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!