gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:51:33 25 4
gpt4 key购买 nike

我想打印 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

最佳答案

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

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

更多详情请见: https://docs.docker.com/compose/compose-file/#variable-substitution

编辑:我还在容器内添加了一个 shell 来扩展变量。

关于docker-compose,无法在docker容器中打印环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022134/

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