By Bobby Iliev
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!
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
-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!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.