1. 程式人生 > 實用技巧 >【Docker】Dockerfile 之 ARG(一)

【Docker】Dockerfile 之 ARG(一)

參考教程:https://docs.docker.com/engine/reference/builder/

環境

  1. virtual box 6.1
  2. centos 7.8
  3. docker 19.03

ARG

ARG <name>[=<default value>]

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value>

flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning.

ARG 指令定義了一個變數,使用者可以在構建時使用 docker build 命令使用--build-arg <varname>=<value> 標誌將其傳遞給構建器。如果使用者指定了未在 Dockerfile 中定義的構建引數,則構建會輸出警告。

[Warning] One or more build-args [foo] were not consumed.

A Dockerfile may include one or more ARG instructions. For example, the following is a valid Dockerfile:

Dockerfile 可能包含一個或多個 ARG 指令。例如,以下是有效的 Dockerfile:

FROM busybox
ARG user1
ARG buildno
# ...

Warning:

It is not recommended to use build-time variables for passing secrets like github keys, user credentials etc. Build-time variable values are visible to any user of the image with the docker history

command.

警告:

不建議使用構建時變數來傳遞諸如 github 金鑰,使用者憑據等機密。構建時變數值對於使用 docker history 命令的映象的任何使用者都是可見的。

預設值

An ARG instruction can optionally include a default value:

ARG 指令可以選擇包含預設值:

FROM busybox
ARG user1=someuser
ARG buildno=1
# ...

If an ARG instruction has a default value and if there is no value passed at build-time, the builder uses the default.

如果 ARG 指令具有預設值,並且在構建時未傳遞任何值,則構建器將使用預設值。

範圍

An ARG variable definition comes into effect from the line on which it is defined in the Dockerfile not from the argument’s use on the command-line or elsewhere. For example, consider this Dockerfile:

ARG 變數從 Dockerfile 中定義的行開始生效,而不是從命令列或其他地方的自變數使用開始。例如,考慮以下 Dockerfile:

FROM busybox
USER ${user:-some_user}
ARG user
USER $user
# ...

A user builds this file by calling:

$ docker build --build-arg user=what_user .

The USER at line 2 evaluates to some_user as the user variable is defined on the subsequent line 3. The USER at line 4 evaluates to what_user as user is defined and the what_user value was passed on the command line. Prior to its definition by an ARG instruction, any use of a variable results in an empty string.

第 2 行的 USER 評估為 some_user,因為在隨後的第 3 行中定義了 USER 變數。第 4 行的 USER 評估為 what_user,因為定義了 user,並且為 what_user 在命令列中傳遞。在通過 ARG 指令對其進行定義之前,對變數的任何使用都會導致一個空字串。

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.

ARG 指令在定義它的構建階段結束時超出範圍。要在多個階段使用變數,每個階段都必須包含 ARG 指令。

FROM busybox
ARG SETTINGS
RUN ./run/setup $SETTINGS

FROM busybox
ARG SETTINGS
RUN ./run/other $SETTINGS

總結

介紹了 Dockerfile 中 ARG 指令的說明,預設值和範圍。