简体   繁体   English

我可以在 docker-compose.yml 文件中设置/获取变量吗?

[英]Can I set/get variables in docker-compose.yml files?

I want to have a variable in a docker-compose.yml for my project that represents a port and instead of putting 8080 everywhere in the file, I'd rather use it as a variable.我想在我的项目docker-compose.yml有一个变量来表示一个端口,而不是将8080放在文件中的任何地方,我宁愿将其用作变量。

Is it possible to set variable, say in the beginning of the file, then reuse it in other places of the file?是否可以在文件的开头设置变量,然后在文件的其他地方重用它?

You can use an external .env file and include it in the docker-compose file.您可以使用外部 .env 文件并将其包含在 docker-compose 文件中。

$ cat .env
port=8080

$ cat docker-compose.yml
version: '3'
services:
  web:
    port: "${port}"

docker-compose.yml and .env should be in the same directory. docker-compose.yml.env应该在同一个目录中。

You can do these steps:您可以执行以下步骤:

  1. Make a file named .env beside your docker-compose.yml file.env docker-compose.yml文件旁边创建一个名为docker-compose.yml文件
  2. Set your variable there as port=8080将您的变量设置为port=8080
  3. Use it inside your docker-compose.yml file as $port or ${port}docker-compose.yml文件中使用它作为$port${port}

Reference 参考

Starting from version 3.4, you can re-use configuration parts using extension fields .从 3.4 版本开始,您可以使用扩展字段重新使用配置部分。 Valid extension fields have two requirements:有效的扩展字段有两个要求:

  1. Should be located at the root of your Compose file.应位于 Compose 文件的根目录。
  2. Their name starts with the "x-" character sequence.它们的名称以“x-”字符序列开头。

Here's an example:下面是一个例子:

version: '3.4'
x-logging:
  &default-logging
  options:
    max-size: '12m'
    max-file: '5'
  driver: json-file

services:
  web:
    image: myapp/web:latest
    logging: *default-logging
  db:
    image: mysql:latest
    logging: *default-logging

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM