gpt4 book ai didi

docker - 在 docker-compose.yml 中重用环境变量

转载 作者:IT老高 更新时间:2023-10-28 12:36:13 24 4
gpt4 key购买 nike

是否可以重复使用在多个容器之间共享的环境变量?

这个想法是为了避免重复,如下例所示:

version: '2'

services:

db:
image: example/db
ports:
- "8443:8443"
container_name: db
hostname: db
environment:
- USER_NAME = admin
- USER_PASSWORD = admin

svc:
image: example/svc
depends_on:
- db
ports:
- "9443:9443"
container_name: svc
hostname: svc
environment:
- DB_URL = https://db:8443
- DB_USER_NAME = admin
- DB_USER_PASSWORD = admin

最佳答案

extends 选项可能不错,但它是 not supported3.x 中编写文件。其他方法是:

  1. Extension fields (撰写文件 3.4+)

    如果您可以使用 3.4+ 撰写文件,扩展字段可能是最佳选择:

    docker-compose.yml

     version: '3.4'

    x-common-variables: &common-variables
    VARIABLE: some_value
    ANOTHER_VARIABLE: another_value

    services:
    some_service:
    image: someimage
    environment: *common-variables

    another_service:
    image: anotherimage
    environment:
    <<: *common-variables
    NON_COMMON_VARIABLE: 'non_common_value'
  2. env_file指令

    docker-compose.yml

     version: '3.2'

    services:
    some_service:
    image: someimage
    env_file:
    - 'variables.env'

    another_service:
    image: anotherimage
    env_file:
    - 'variables.env'

    variables.env

     VARIABLE=some_value
    ANOTHER_VARIABLE=another_value
  3. .env file在项目根目录(或实际撰写环境中的变量)

    .env 文件中的变量可以在服务配置中引用:

    docker-compose.yml

     version: '3.2'

    services:
    some_service:
    image: someimage
    environment:
    - VARIABLE

    another_service:
    image: anotherimage
    environment:
    - VARIABLE
    - ANOTHER_VARIABLE

    .env

     VARIABLE=some_value
    ANOTHER_VARIABLE=another_value

关于docker - 在 docker-compose.yml 中重用环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36283908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com