Why can't I use the build arg again after FROM

2019-02-18 21:46发布

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

It works for the second line (FROM), but it behaves like it is unset in the COPY line:

Step 1/3 : ARG FROM_IMAGE=ubuntu:bionic Step 2/3 : FROM $FROM_IMAGE ---> 8626492fecd3 [...] Step 3/3 : COPY sources_list/${SOURCES_LIST_FILE} /etc/apt/sources.list failed to copy files: failed to copy directory: mkdir /var/lib/docker/overlay2/0536b4e280ddca2fec18db9d79fa625a8be86efdbaaea5b3dbbefcdaaab3f669/merged/etc/apt/sources.list: not a directory

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

Step 4/4 : COPY sources_list/${SOURCES_LIST_FILE} /etc/apt/sources.list ---> 7f974fffe929

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.

1条回答
何必那么认真
2楼-- · 2019-02-18 22:09

Why can't I use the FROM_IMAGE build arg twice, on and after a FROM line?

There is a real difference depending on where you put ARG related to FROM line:

  • any ARG before the first FROM can be used in any FROM line
  • any ARG within a build stage (after a FROM) can be used in that build stage

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

查看更多
登录 后发表回答