我希望能够在docker-compose中使用env变量。Yml,在docker-compose up时传入的值。这就是例子。

今天我使用的是基本的docker run命令,该命令包含在我自己的脚本中。 有没有一种方法来实现它与撰写,没有任何这样的bash包装?

proxy:
  hostname: $hostname
  volumes:
    - /mnt/data/logs/$hostname:/logs
    - /mnt/data/$hostname:/data

当前回答

使用.env文件在docker-compse.yml中定义动态值。不管是port还是其他值。

示例docker-compose:

testcore.web:
       image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
       volumes: 
            - c:/logs:c:/logs
       ports:
            - ${TEST_CORE_PORT}:80
       environment:
            - CONSUL_URL=http://${CONSUL_IP}:8500 
            - HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}

在.env文件中,你可以定义这些变量的值:

CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002

其他回答

我有一个简单的bash脚本,我为此创建,这只是意味着在使用之前在你的文件上运行它: https://github.com/antonosmond/subber

基本上只要创建你的合成文件使用双花括号表示环境变量,例如:

app:
    build: "{{APP_PATH}}"
ports:
    - "{{APP_PORT_MAP}}"

双花括号中的任何内容都将被同名的环境变量替换,因此如果我设置了以下环境变量:

APP_PATH=~/my_app/build
APP_PORT_MAP=5000:5000

运行subber docker-compose。Yml生成的文件看起来像这样:

app:
    build: "~/my_app/build"
ports:
    - "5000:5000"

以下代码适用于docker-compose 3.x 在容器内设置环境变量

方法- 1直接法

web:
  environment:
    - DEBUG=1
      POSTGRES_PASSWORD: 'postgres'
      POSTGRES_USER: 'postgres'

方法- 2“。env”文件

在docker-compose.yml文件所在的位置创建一个.env文件

$ cat .env
TAG=v1.5
POSTGRES_PASSWORD: 'postgres'

你的合成文件会是这样的

$ cat docker-compose.yml
version: '3'
services:
  web:
    image: "webapp:${TAG}"
    postgres_password: "${POSTGRES_PASSWORD}"

从1.25.4开始,docker-compose支持——env-file选项,允许你指定一个包含变量的文件。

你的简历应该是这样的:

hostname=my-host-name

和命令:

docker-compose --env-file /path/to/my-env-file config
env SOME_VAR="I am some var" OTHER_VAR="I am other var" docker stack deploy -c docker-compose.yml

使用3.6版本:

version: "3.6"
services:
  one:
    image: "nginx:alpine"
    environment:
      foo: "bar"
      SOME_VAR:
      baz: "${OTHER_VAR}"
    labels:
      some-label: "$SOME_VAR"
  two:
    image: "nginx:alpine"
    environment:
      hello: "world"
      world: "${SOME_VAR}"
    labels:
      some-label: "$OTHER_VAR"

我从这个链接得到的 https://github.com/docker/cli/issues/939

使用.env文件在docker-compse.yml中定义动态值。不管是port还是其他值。

示例docker-compose:

testcore.web:
       image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
       volumes: 
            - c:/logs:c:/logs
       ports:
            - ${TEST_CORE_PORT}:80
       environment:
            - CONSUL_URL=http://${CONSUL_IP}:8500 
            - HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}

在.env文件中,你可以定义这些变量的值:

CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002