docker-compose,无法在docker容器中打印环境变量

时间:2018-06-25 11:12:55

标签: docker docker-compose

我要打印在docker-compose文件中定义的环境变量。

这是我的docker-compose-1.yml

version: '3.6'

services:
  busybox:
    image: busybox
    command: 'echo $DEBUG'
    environment:
      - DEBUG='123456'

然后,尝试在docker容器中打印DEBUG环境变量:

☁  environment-variables-in-compose [master] ⚡  docker-compose -f docker-compose-1.yml up
WARNING: The DEBUG variable is not set. Defaulting to a blank string.
Creating network "environmentvariablesincompose_default" with the default driver
Creating environmentvariablesincompose_busybox_1 ... done
Attaching to environmentvariablesincompose_busybox_1
busybox_1  |
environmentvariablesincompose_busybox_1 exited with code 0

如您所见,得到WARNING: The DEBUG variable is not set. Defaulting to a blank string.

我错了吗?

更新1:

docker-compose-1.yml

version: '3.6'

services:
  busybox:
    image: busybox
    command: 'echo $$DEBUG'
    environment:
      DEBUG: 123456

我使用双command符号更改了$,但结果仍然不是我想要的。

☁  environment-variables-in-compose [master] ⚡  docker-compose -f docker-compose-1.yml up
Creating network "environmentvariablesincompose_default" with the default driver
Creating environmentvariablesincompose_busybox_1 ... done
Attaching to environmentvariablesincompose_busybox_1
busybox_1  | $DEBUG
environmentvariablesincompose_busybox_1 exited with code 0

如您所见,环境变量打印为$DEBUG,而不是预期值123456

1 个答案:

答案 0 :(得分:6)

Compose将从您正在运行compose的环境中扩展变量。要在您的容器内展开变量,请使用$转义$$

command: '/bin/sh -c "echo $$DEBUG"'

有关更多详细信息,请参见:https://docs.docker.com/compose/compose-file/#variable-substitution

编辑:我还在容器内添加了一个外壳以扩展变量。