> For the complete documentation index, see [llms.txt](https://camelgemonion.gitbook.io/docker/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://camelgemonion.gitbook.io/docker/dockerfile-zhi-ling/arg/scope-zuo-yong-yu.md).

# Scope（作用域）

**ARG**变量的定义从**Dockerfile**中定义该变量的行开始生效，而不是从命令行参数或其他地方的使用中生效。例如，请思考此**Dockerfile**：

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

一个用户构建镜像时执行了下面的命令：

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

第二行的**USER**的值会计算为**some\_user**，因为**user**变量在随后的第三行中被定义了。第四行的**USER**值会计算为**what\_user**，因为**user**已经被定义了并且通过命令行将**what\_user**将值传递给了变量。在 **ARG指令**定义变量之前，任何对该变量的引用都会产生一个空字符串。

**ARG指令**在定义该指令的构建阶段结束时超出了范围。要在多个阶段使用**ARG**，每个阶段必须包含 **ARG指令**。

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

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

demo:

```
ARG VERSION=7
FROM centos:$VERSION
ARG NAME="TonyYang"
ARG AGE=31
RUN echo ${NAME} is ${AGE} years old.; \
    echo "Here is the first build stage"

FROM centos:$VERSION
ARG NAME
ARG AGE
RUN echo ${NAME} is ${AGE} years old.;\
    echo "Here is the second build stage."
```

```bash
docker build --no-cache --build-arg NAME=camelgem --build-arg AGE=30 -f Dockerfile.scopeofARG  -t camelgem/arg:v1 .
```

如果多个阶段定义了相同名称的**ARG**变量，当从命令行参数传入新的**ARG**值时，所有阶段的默认值都会被新传入的值覆盖。

上面两个阶段的输出都为TonyYang is 31 years old。
