anatoly techtonik
anatoly techtonik

Reputation: 20521

echo environment variable with docker run

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

Upvotes: 10

Views: 8250

Answers (1)

Robert
Robert

Reputation: 36763

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.

Upvotes: 9

Related Questions