在多阶段 Dockerfile 中共享变量:FROM 之前的 ARG 未被替换

Share variable in multi-stage Dockerfile: ARG before FROM not substituted

我正在为 darshan utils:

编写多阶段 Dockerfile
ARG DARSHAN_VER=3.1.6

FROM fedora:29 as build
RUN dnf install -y \
        gcc \
        make \
        bzip2 bzip2-devel zlib zlib-devel
RUN curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz" \
    && tar ...


FROM fedora:29
COPY --from=build "/usr/local/darshan-${DARSHAN_VER}" "/usr/local/darshan-${DARSHAN_VER}"
...

我用 docker build -t darshan-util:3.6.1 . 构建它,我得到的错误是:

Step 5/10 : RUN curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz"     && tar ...

 ---> Running in 9943cce1669c
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
...
curl: (78) RETR response: 550
The command '/bin/sh -c curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz"     && tar ...' returned a non-zero code: 78

我想在两个阶段重用同一个 ARG,这样我就可以只定义一次默认构建变量。 如果我在两个阶段复制 ARG,就在两个 FROM 的下方,它会正确构建。

使用默认值定义 "global" 多级 ARG 变量的正确方法是什么?

A​​RG 仅在单个图像的构建阶段有效。 对于多阶段,只需声明即可更新 ARG:

ARG DARSHAN_VER

在您的 FROM 指令之后。

比照。 https://docs.docker.com/engine/reference/builder/#arg

ARG DARSHAN_VER=3.1.6

FROM fedora:29 as build
ARG DARSHAN_VER
RUN dnf install -y \
        gcc \
        make \
        bzip2 bzip2-devel zlib zlib-devel
RUN curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz" \
    && tar ...


FROM fedora:29
ARG DARSHAN_VER
COPY --from=build "/usr/local/darshan-${DARSHAN_VER}" "/usr/local/darshan-${DARSHAN_VER}"
...

以下是文档中的引述:

An ARG instruction goes out of scope at the end of the build stage where it was defined. To use an arg in multiple stages, each stage must include the ARG instruction.

https://docs.docker.com/engine/reference/builder/#scope

An ARG declared before a FROM is outside of a build stage, so it can’t be used in any instruction after a FROM. To use the default value of an ARG declared before the first FROM use an ARG instruction without a value inside of a build stage

https://docs.docker.com/engine/reference/builder/#understand-how-arg-and-from-interact