Environment variables in Docker

How can I set an env var inside a Docker container?

You can use the --env (or -e) flag when running the container:

docker run --env MY_VAR=my_value alpine printenv MY_VAR

This command will:

  1. Set the environment variable MY_VAR to the value my_value before running an Alpine container.
  2. Print the value of the env var MY_VAR inside that container.

Can I pass env vars already defined in my shell to a Docker container?

Yes, if you don't set a value when using the --env flag, Docker will read the value of the env var from your shell if it's defined:

export MY_VAR=new_value
docker run --env MY_VAR alpine printenv MY_VAR

The second command will set the env var MY_VAR to the value defined in the first command before running the container.

Can I set multiple env vars inside a Docker container?

Yes, you can use the --env flag multiple times:

docker run --env MY_VAR1=my_value1 --env MY_VAR2=my_value2 alpine printenv

This command will set the env vars MY_VAR1 and MY_VAR2 before running the container and print all the env vars defined inside that container.

Is there a more convenient way if I want to set many env vars inside a Docker container?

Yes, you can use the --env-file flag to pass a file containing multiple env vars to a Docker container:

echo -e 'MY_VAR1=my_value1\nMY_VAR2=my_value2' > my-env-vars.txt

This command will create a file called my-env-vars.txt with 2 env vars defined: MY_VAR1=my_value1 and MY_VAR2=my_value2.

docker run --env-file my-env-vars.txt alpine printenv

This command will set the env vars defined in the file my-env-vars.txt before running a container and print all the env vars defined inside that container.

Can I set default values for env vars in a Docker image?

Yes, you can set default values for env vars using the ENV instruction in a Dockerfile.

More info

External links: