英文:
Why variable assignment doesn't work as expected in docker-compose commands?
问题
以下是翻译后的内容:
我在我的docker-compose.yml文件中有以下内容:
my-service:
image: amazon/aws-cli
entrypoint: /bin/sh -c
command: >
'
a=1899
echo "The value of \"a\" is $a"
'
当我运行它时,我看到The value of "a" is .
,所以出于某种原因,变量赋值不像我期望的那样工作。你知道发生了什么吗?
我尝试简化我的Docker Compose到最小程度,但问题仍然存在。我期望变量赋值和输出与bash脚本中的相同。
英文:
I have the following in my docker-compose.yml:
my-service:
image: amazon/aws-cli
entrypoint: /bin/sh -c
command: >
'
a=1899
echo "The value of \"a\" is $a"
'
And when I run it, I see The value of "a" is .
, so for some reason, the variable assignment is not working as I would expect. Do you know what's going on?
I tried simplifying my docker compose to the very minimum, but still the same problem. I would expect that variable assignment and outputing would be the same than in a bash script.
答案1
得分: 1
你需要转义$
符号。如果不转义这个符号,那么它将尝试从主机环境而不是Docker容器内部获取值。
所以你可以将你的命令更改为:
my-service:
image: amazon/aws-cli
entrypoint: /bin/sh -c
command: >
'
a=1899
echo "The value of \"a\" is $$a"
'
如果你想要从主机传递它,你可以这样做:
my-service:
image: amazon/aws-cli
entrypoint: /bin/sh -c
command: >
'
echo "The value of \"a\" is $a"
'
a=1899 docker-compose up
英文:
You will need to escape the $
sign. If you do not escape the sign, then it will try to take the value from your host environment rather that from inside the docker container.
So you can change your command to
my-service:
image: amazon/aws-cli
entrypoint: /bin/sh -c
command: >
'
a=1899
echo "The value of \"a\" is $$a"
'
If you want to pass it from host instead, you can do this instead
my-service:
image: amazon/aws-cli
entrypoint: /bin/sh -c
command: >
'
echo "The value of \"a\" is $a"
'
a=1899 docker-compose up
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论