Can anybody explain why this doesn't work:
# docker run -ti --rm golang echo $GOPATH
# docker run -ti --rm golang echo \$GOPATH
$GOPATH
when this works:
# docker run -ti --rm golang bash -c "echo \$GOPATH"
/go
Using –env, -e When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.
Dockerfile provides a dedicated variable type ENV to create an environment variable. We can access ENV values during the build, as well as once the container runs.
Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable.
Fetch Using docker exec Command Here, we are executing the /usr/bin/env utility inside the Docker container. Using this utility, you can view all the environment variables set inside Docker containers.
1)
docker run -ti --rm golang echo $GOPATH
docker run -ti golang echo $GOPATH
/Users/me/go
I removed the --rm
flag to be able to inspect the container. Then, I did docker inspect container-id
:
"Env": [
"no_proxy=*.local, 169.254/16",
"PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOLANG_VERSION=1.8.1",
"GOPATH=/go"
],
"Cmd": [
"echo",
"/Users/me/go"
],
$GOPATH
is expanded before the container starts. It's expanded by your shell, indeed before the docker
command is called.
2)
docker run -ti --rm golang echo \$GOPATH
docker run -ti golang echo \$GOPATH
$GOPATH
docker inspect container-id
:
"Env": [
"no_proxy=*.local, 169.254/16",
"PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOLANG_VERSION=1.8.1",
"GOPATH=/go"
],
"Cmd": [
"echo",
"$GOPATH"
],
Here the $GOPATH
is a literal string and doesn't get expanded by the shell because you escaped the $
, then echo
receives the literal var name instead of its value.
3)
docker run -ti --rm golang bash -c "echo \$GOPATH"
docker run -ti golang bash -c "echo \$GOPATH"
/go
docker inspect container-id
:
"Env": [
"no_proxy=*.local, 169.254/16",
"PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOLANG_VERSION=1.8.1",
"GOPATH=/go"
],
"Cmd": [
"bash",
"-c",
"echo $GOPATH"
],
Here, your shell runs docker with no variable expansion too, due to the \$
, but there is another shell that will catch it and expand it: bash
will do that but inside the container this time, where the GOPATH is provided by docker as environment variable defined in the golang
image (GOPATH=/go). See the Dockerfile where that is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With