Get Environment Variable from Docker Container

Citronen picture Citronen · Dec 2, 2015 · Viewed 161.8k times · Source

What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile?

For instance, an environment variable that has been set through some docker exec container /bin/bash session?

I can do docker exec container env | grep ENV_VAR, but I would prefer something that just returns the value.

I've tried using docker exec container echo "$ENV_VAR", but the substitution seems to happen outside of the container, so I don't get the env var from the container, but rather the env var from my own computer.

Thanks.

Answer

jwodder picture jwodder · Dec 2, 2015

The proper way to run echo "$ENV_VAR" inside the container so that the variable substitution happens in the container is:

docker exec <container_id> bash -c 'echo "$ENV_VAR"'