I’ve seen this being asked quite a bit, so I’ve decided to write this answer outlining a few ways how to pass environment variables to a Docker container.
Hope that this is helpful! If you have any questions post the below!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
-e
flagThe -e
flag can be used to pass environment variables to a Docker container.
For example, if you want to pass the environment variable MY_ENV_VAR
to the container, you can do the following:
docker run -e "MY_ENV_VAR=some_value" image-name
The -e
is short for --env
, so you can also use that instead:
docker run --env "MY_ENV_VAR=some_value" image-name
The -e
flag can be used multiple times to pass multiple environment variables:
docker run -e "MY_VAR_1=some_value1" -e "MY_VAR_2=some_value2" -e "MY_VAR_3=some_value3" image-name
The same can be achieved with docker-compose
:
docker-compose run -e MY_ENV_VAR=some_value
--env-file
flagIf you want to pass a file containing all of your environment variables to a Docker container, you can use the --env-file
flag.
The --env-file
flag allows you to pass a file containing environment variables to a Docker container.
Let’s say that you have a .env
file containing the following environment variables:
MY_ENV_VAR=some_value
MY_SECOND_ENV_VAR=some_other_value
MY_THIRD_ENV_VAR=yet_another_value
Rather than passing the environment variables directly to the container, you can pass the .env
file to the container using the --env-file
flag:
docker run --env-file .env image-name
Alternatively, if you are using docker-compose
, you can do the same thing:
docker-compose --env-file .env up
docker-compose.yml
If you are using docker-compose
to manage your Docker containers, you can pass environment variables to the container using the environment
key in the docker-compose.yml
file.
For example:
version: '3'
services:
my-container:
image: image-name
environment:
MY_ENV_VAR: some_value
MY_SECOND_ENV_VAR: some_other_value
MY_THIRD_ENV_VAR: yet_another_value
For more information, see the Docker Compose documentation.
Hope that this helps!
Click below to sign up and get $100 of credit to try our products over 60 days!