# Variable substitution

配置选项可以包含环境变量。 Compose使用运行docker-compose的shell环境中的变量值。例如，假设shell包含POSTGRES\_VERSION=9.3，并且我们提供了以下配置：

```
db:
  image: "postgres:${POSTGRES_VERSION}"
```

当使用此配置运行docker-compose时，Compose在shell程序中查找POSTGRES\_VERSION环境变量并替换其值。对于本示例，Compose在运行配置之前将映像镜像解析为postgres: 9.3。

如果未设置环境变量，则Compose替换为空字符串。在上面的示例中，如果未设置POSTGRES\_VERSION，则image选项的值为postgres:。

我们可以使用.env文件设置环境变量的默认值，该文件会自动在项目目录（Compose文件的父文件夹）中查找。在shell环境中设置的值将覆盖.env文件中设置的值。

{% hint style="info" %}
.env文件功能仅在使用docker-compose up命令时有效，而不适用于docker stack deploy。
{% endhint %}

$VARIABLE和${VARIABLE}语法均受支持。此外，当使用2.1文件格式时，可以使用Shell语法提供内联默认值：

* 如果在当前环境中，VARIABLE的值没有设置或者为空值，${VARIABLE:-default}被计算为default。
* 只有当VARIABLE的值在当前环境中没有设置时，${VARIABLE-default}会被计算为default。

同样，以下语法允许我们指定必要变量：&#x20;

* 如果在当前环境中，VARIABLE的值没有设置或者为空，则${VARIABLE:?err}会以指定的err错误消息退出。&#x20;
* 如果当前环境中，VARIABLE的值没有设置，则${VARIABLE?err}会以指定的err错误消息退出。

其他扩展的shell风格特性, 例如像${VARIABLE/foo/bar}并不支持。

当我们的配置需要一个字面量的$符号时，可以使用一个$$符号。这种写法也可以防止Compose内插一个值，因此，$$允许我们引用一个不想被Compose处理的环境变量。

```
web:
  build: .
  command: "$$VAR_NOT_INTERPOLATED_BY_COMPOSE"
```

如果没有使用$$符号，而是使用了$符号，Compose会将该其作为环境变量进行解释，然后发出一个警告：

```
The VAR_NOT_INTERPOLATED_BY_COMPOSE is not set. Substituting an empty string.
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://camelgemonion.gitbook.io/docker/dockercompose.yaml-wen-jian-zhong-chang-yong-zhi-ling/untitled-12/variable-substitution.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
