1

为什么作为入口点运行的命令看不到环境变量?
例子:

$docker run -it -e "name=JD" --entrypoint 'echo' ubuntu 'Hello $name'
Hello $name  
$ docker run -it -e "name=JD" --entrypoint 'echo' ubuntu "Hello $name"
Hello  

但是当我启动 shell 时,环境变量就在那里:

$ docker run -it -e "name=JD" ubuntu /bin/bash
root@c3e513390184:/# echo "$name"
JD

为什么在使用echoas 入口点的第一种情况下它没有找到 env 变量集?

4

1 回答 1

0

First case

docker run -it -e "name=JD" --entrypoint 'echo' ubuntu 'Hello $name'

Single quotation mark always prevents string from variable expansion. Whatever you write in single quotes remains unchanged. Try echo '$PWD' in your terminal and you will see $PWD as the output. Try echo "$PWD" and you will get your working directory printed.

Second case

docker run -it -e "name=JD" --entrypoint 'echo' ubuntu "Hello $name"

Your code is being expanded before running Docker. Your shell expands whole string and then executes it. At this moment you dont have $name declared and you get it empty. That means inside container you get "Hello " command, not "Hello $name".

If you want to echo environment variable from inside container, simplest way is to wrap script into sh-file to prevent its expansion and pass this file to container.

Third case is obvious I guess and doesn't need explanation.

于 2019-01-18T16:06:03.470 回答