Set environment variables (original) (raw)

Set environment variables within your container's environment

A container's environment is not set until there's an explicit entry in the service configuration to make this happen. With Compose, there are two ways you can set environment variables in your containers with your Compose file.

Don't use environment variables to pass sensitive information, such as passwords, in to your containers. Use secrets instead.

You can set environment variables directly in your container's environment with theenvironment attribute in your compose.yaml.

It supports both list and mapping syntax:

is equivalent to

Seeenvironment attribute for more examples on how to use it.

Additional information

The value of the DEBUG variable in the container is taken from the value for the same variable in the shell in which Compose is run. Note that in this case no warning is issued if the DEBUG variable in the shell environment is not set.

A container's environment can also be set using .env files along with theenv_file attribute.

Using an .env file lets you use the same file for use by a plain docker run --env-file ... command, or to share the same .env file within multiple services without the need to duplicate a long environment YAML block.

It can also help you keep your environment variables separate from your main configuration file, providing a more organized and secure way to manage sensitive information, as you do not need to place your .env file in the root of your project's directory.

Theenv_file attribute also lets you use multiple .env files in your Compose application.

The paths to your .env file, specified in the env_file attribute, are relative to the location of your compose.yaml file.

Interpolation in .env files is a Docker Compose CLI feature.

It is not supported when running docker run --env-file ....

Additional information

Similar to docker run --env, you can set environment variables temporarily with docker compose run --env or its short form docker compose run -e:

Additional information

The value of the DEBUG variable in the container is taken from the value for the same variable in the shell in which Compose is run or from the environment files.