Environment variables set outside the shell, through ~/.bash_profile or ~/.bashrc do not appear to docker, or env, despite being accessible in the shell.
Bash_profile contains the line TEST_ENV_VAR=123
, after restarting terminal, the variable can be accessed through $TEST_ENV_VAR
, however docker and env cannot access this environment variable.
Henrys-MacBook-Pro:~ henry$ echo $TEST_ENV_VAR
123
Henrys-MacBook-Pro:~ henry$ docker run -it -e TEST_ENV_VAR ubuntu env | grep TEST_ENV_VAR
Henrys-MacBook-Pro:~ henry$ env | grep TEST_ENV_VAR
And yet the terminal can access it, and even pass it into docker:
Henrys-MacBook-Pro:~ henry$ docker run -it -e TEST_ENV_VAR=${TEST_ENV_VAR} ubuntu env | grep TEST_ENV_VAR
TEST_ENV_VAR=123
And the issue isn't an issue with environment variable in general, as variables set in the terminal work as expected:
Henrys-MacBook-Pro:~ henry$ export TEST_ENV_VAR=1234
Henrys-MacBook-Pro:~ henry$ docker run -it -e TEST_ENV_VAR ubuntu env | grep TEST_ENV_VAR
TEST_ENV_VAR=1234
I'm running macOS Mojave, 10.14.5, classic terminal, docker 19.03.4, the output of ls -al ~:
-rw-r--r-- 1 henry staff 455 Nov 12 11:50 .bash_profile
docker
doesn't actually start a container. Instead, it sends a message to the Docker engine (running in a separate environment unrelated to the environment in which docker
is executed) requesting that it start a container for you. As such, the new container won't inherit any of variables in your current shell environment.
With your TEST_ENV_VAR=${TEST_ENV_VAR}
attempt, you are explicitly telling docker
to create an environment variable named TEST_ENV_VAR
, with the value produced by expanding TEST_ENV_VAR
now , in the new container, rather than trying to inherit the variable from the appropriate environment.
Even ignoring that, you aren't actually creating an environment variable with TEST_ENV_VAR=123
; you've only created an ordinary shell variable. For env
to see it, you need to first export it.
$ TEST_ENV_VAR=123
$ env | grep TEST_ENV_VAR
$ export TEST_ENV_VAR
$ env | grep TEST_ENV_VAR
TEST_ENV_VAR=123
The.bash_profile is for your user. Docker is running in its own environment (as opposed to running in a subshell spawned by your user). Export only sends information down into child shells. You need to make the variable available at a higher level.
/etc/environment
Be careful in there.
Alternatively, you may look into asking Docker to make these changes itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.