Docker echo environment variable

2020-07-05 06:21发布

I'm trying to write a little docker file that sets a User and just echos the current user as a little example to prove to myself it is working. I've tried a number of variants and couldn't find much help in the documentation.

FROM ubuntu
USER daemon
# ENTRYPOINT ["echo", "$USER"]
# just gives "$USER"
# ENTRYPOINT ["echo", "-e", "${USER}"]
# just gives "$USER"
# ENTRYPOINT echo $USER
# gives empty string
# ENTRYPOINT ["/bin/echo", "$USER"]
# just gives "$USER"

I'm running docker build . on the dockerfile and then running docker run <image-id> and getting the results

Expected result is daemon, or without the USER daemon line, I expect root. Probably a really simple answer.

标签: go docker
3条回答
相关推荐>>
2楼-- · 2020-07-05 06:50

This is the expected behavior, as weird as it seems!

When ENTRYPOINT is a list (as in ENTRYPOINT ["echo", "$USER"]), it is used as-is, without further parsing or interpretation. So $USER remains $USER, because there is no shell involved in the process to replace it with the value of the USER environment variable.

Now, when ENTRYPOINT is a string (as in ENTRYPOINT echo $USER), what is actually executed is sh -c "echo $USER", and $USER is replaced with the value of the environment variable (as you would expect).

However, the environment variable USER is not set by default. It is set by the login process; and when you just run sh -c ... the login process is not involved.

Compare the environment when running docker run -t -i ubuntu bash and docker run -t -i ubuntu login -f root. In the former case, you will get a very basic environment; in the latter case, you will get the complete environment that you are used to (including USERvariable).

查看更多
对你真心纯属浪费
3楼-- · 2020-07-05 06:50

Couldn't you set, in the Dockerfile, the ENV command to a default value, and then, when run-ning a container, use the -e, --env dictionary to override what would be interpreted by the:

ENTRYPOINT echo $SOMEENVVAR

form of ENTRYPOINT?

查看更多
虎瘦雄心在
4楼-- · 2020-07-05 07:05

I think there´s a series of issues here.

when I

docker run -i -t ubuntu /bin/bash
echo $USER
set

I don´t see $USER set at all - whoami does report daemon though.

additionally, I have the suspicion (but have not looked at the code yet) that ENV vars in the Dockerfile are escaped, to avoid their use (many people assume that they can export host variables to the built container, but this is something that the docker guys would like to avoid)

查看更多
登录 后发表回答