Question

How to pass environment variables to a Docker container?

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!


Submit an answer

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!

Sign In or Sign Up to Answer

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.

Accepted Answer

Set environment variable with the -e flag

The -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

Set environment variable with the --env-file flag

If 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

Set environment variable within 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!

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.