Spring fancy
Spring fancy

Reputation: 323

Enviroment variables in docker containers - how does it work?

I can't understand some thing, namely as we know we can pass to docker run argument -e SOME_VAR=13.
Then each process launched (for example using docker exec ping localhost -c $SOME_VAR=13) can see this variable.

How does it work ? After all, enviroment are about bash, we don't launched bash. I can't understand it. Can you explain me how -e does work without shell ?

For example, let's look at following example:

[user@user~]$ sudo docker run -d -e XYZ=123 ubuntu sleep 10000
2543e7235fa9
[user@user~]$ sudo docker exec -it 2543e7235fa9 echo test
test
[user@user~]$ sudo docker exec -it 2543e7235fa9 echo $XYZ
<empty row>      

Why did I get <empty row> instead of 123 ?

Upvotes: 0

Views: 57

Answers (2)

Patrik Iselind
Patrik Iselind

Reputation: 327

The environment is not specific to shells. Even ordinary processes have environments. They work the same for both shells and ordinary processes. This is because shells are ordinary processes.

When you do SOMEVAR=13 someBinary you define an environment variable called SOMEVAR for the new process, someBinary. You do this with -e in docker because you ask another process to start your process, the docker daemon.

Upvotes: 0

johnharris85
johnharris85

Reputation: 18926

The problem is that your $XYZ is getting interpolated in the host shell environment, not your container.

$ export XYZ=456
$ docker run -d -e XYZ=123 ubuntu sleep 10000
$ docker exec -it $(docker ps -ql) echo $XYZ
$ 456
$ docker exec -it $(docker ps -ql) sh -c 'echo $XYZ'
$ 123

You have to quote it so it's passed through as a string literal to the container. Then it works fine.

Upvotes: 2

Related Questions