Problem
When running a command through docker exec
, environment variables used in the command are usually replaced with values from the host system, not the container itself.
However, it is sometimes useful to leverage the environment variables that are defined inside the container itself.
For example, to run a database backup script, you could use the database parameter environment variables already defined inside the container.
Solution
The trick is to run the command through the container's shell and wrap the command string in single quotes (not double quotes).
docker exec <container_name> /bin/sh -c 'echo $MY_ENV_VAR'
This is essentially a way to have the shell inside the container evaluate a string as a command.
Details
For the examples below, assume that the value of the MY_ENV_VAR
environment variable is as follows:
val_inside
- inside the containerval_outside
- outside the container
Double Quote
docker exec <container_name> /bin/sh -c "echo $MY_ENV_VAR"
When using double quotes, the environment variable is converted to a value before being sent to the container. This means that the command that actually runs on the container is echo val_outside
.
This behaviour is the same as running the command without using the container's shell. The command below will behave in the exact same way:
docker exec <container_name> echo $MY_ENV_VAR
If the environment variable has not been defined on the host system, it is replaced with an empty string.
Single Quote
docker exec <container_name> /bin/sh -c 'echo $MY_ENV_VAR'
When using single quotes, the environment variable is only converted to a value inside the container. In this case, the command will print val_inside
.