问题
I am trying to provide a dynamically generated list of --env VAR1 --env VAR2 --env-file env.list
environment variables to docker run
.
Unfortunately it is not working.
- for
--env
mapped variables, the variables are not visible in the container. - for
--env-file
provided file, docker complains that it cannot find the file:docker: open "env.list": no such file or directory.
Details
Running:
# env_params contains either --env or --env-file arguments
MY_VAR=123
env_params='--env "MY_VAR"'
echo ${env_params}
docker run -it --rm \
${env_params} \
my_docker_image env | grep MY_VAR
will not output anything. MY_VAR
is not visible inside the container. But:
MY_VAR=123
docker run -it --rm \
--env "MY_VAR" \
my_docker_image env | grep MY_VAR
will work and 123
will be printed.
In a similar way --env-file
will not work when provided through env_params
but will work when provided directly to the docker run
command.
What am I doing wrong?
回答1:
There are two issues here.
First, When you run, in your shell:
MY_VAR=123
You have not set an environment variable. You have set a local shell variable. When you use --env MY_VAR
, you are telling Docker that you want to make the environment variable MY_VAR
available inside the container, and since it doesn't exist you get nothing:
$ MY_VAR=123
$ docker run -it --rm -e MYVAR alpine env | grep MY_VAR
<crickets>
If you first export that to the environment:
$ export MY_VAR=123
$ docker run -it --rm -e MYVAR alpine env | grep MY_VAR
MY_VAR=123
Then it will work as you expect. Alternately, you can use the VARNAME=VARVALUE
form of the --env
option:
docker run -e "MY_VAR=${MY_VAR}" ...
The second issue has to do with how shell variable interpolation works. If you have:
env_params='--env "MY_VAR"'
docker run -it --rm \
${env_params} \
alpine env
Then the resulting command line is:
docker run -it --rm --env '"MY_VAR"' alpine env
That is, the argument you're passing to docker run
includes literal double quotes. You can fix that through the use of the eval
statement (keeping in mind that you'll need to modify your script to export MY_VAR
):
eval docker run -it --rm \
${env_params} \
alpine env | grep MY_VAR
Alternately (and I would argue preferably) you can use your env_params
variable as an array, as long as you're using bash
:
env_params=(--env MY_VAR)
env_params+=(--env SOME_OTHER_VAR)
docker run -it --rm \
"${env_params[@]}" \
alpine env | grep MY_VAR
Which would result in the correct command line:
docker run -it --rm --env MY_VAR --env SOME_OTHER_VAR alpine env
I guess the summary here is that your issues ultimately have nothing to do with "how docker run
interprets dynamically generated arguments", but have everything to do with "how shell variables and interpolation work".
来源:https://stackoverflow.com/questions/48807931/how-does-docker-run-interpret-dynamically-generated-env-arguments