---
title: "Taking Advantage of the docker-compose Environment Variables"
description: "Learn in this article the different ways of declaring docker-compose environment variables. Discover the great flexibility Docker allows in declaring the environment variables."
canonical: "https://adamtheautomator.com/docker-compose-environment-variables/"
---

# Taking Advantage of the docker-compose Environment Variables

> Learn in this article the different ways of declaring docker-compose environment variables. Discover the great flexibility Docker allows in declaring the environment variables.

Source: https://adamtheautomator.com/docker-compose-environment-variables/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Taking Advantage of the docker-compose Environment Variables](https://adamtheautomator.com/wp-content/uploads/2021/09/How-to-Use-Environment-Variables-in-Docker-Compose.jpg)

# Taking Advantage of the docker-compose Environment Variables

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)15 September 20218 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Docker](/tag/docker/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Declaring Environment Variables in the Docker Compose File](#declaring-environment-variables-in-the-docker-compose-file)
*   [Substituting the Environment Variables](#substituting-the-environment-variables)
*   [Using Multiple Environment Variables Files for Multiple Environments](#using-multiple-environment-variables-files-for-multiple-environments)
*   [Incorporating the env\_file in the Docker Compose File](#incorporating-the-env_file-in-the-docker-compose-file)
*   [Conclusion](#conclusion)

If you need to define various configuration values, environment variables are your best friend. Like many tools, Docker and, more specifically, [Docker Compose](https://docs.docker.com/compose/) can both define and read environment variables to help keep your configurations clean and modular. This tutorial teaches you how to use `docker-compose` environment variables to define different containers, environments, and more.

## **Prerequisites**

If you’d like to follow along step-by-step, ensure you have the following:

*   A Linux host with admin privileges. This tutorial uses [Ubuntu 18.04.5 LTS](https://releases.ubuntu.com/18.04/).
*   [Docker](https://adamtheautomator.com/docker-ubuntu/) installed on the Linux host. This tutorial uses Docker v19.03.11.

Related:[How to Install and Use Docker on Ubuntu (In the Real World)](https://adamtheautomator.com/docker-ubuntu/)

## Declaring Environment Variables in the Docker Compose File

Containers can demand a lot of configuration. And not every configuration in your containers will be unique. Some settings might be shared across some of your containers, like a MySQL database credential. Store the credentials manually in each container, and when the credentials change, you end up having to update the credentials multiple times.

Environment variables can reduce that hassle. Store those shared settings as environment variables! Reference the environment variables instead of repeating yourself in the containers. When the credentials change, you have to update just one setting: the environment variable.

Let’s start by declaring an environment variable and storing it in the Docker Compose file itself. The steps below will store settings for a hypothetical MySQL database in environment variables.

1\. Open a terminal on your local machine.

2\. Create a folder named ~/_docker-compose-demo,_ then change (`cd`) the working directory to the folder you just created. The ~/_docker-compose-demo_ folder will contain all of the files you’ll create in this tutorial.

```bash
mkdir ~/docker-compose-demo
cd ~/docker-compose-demo
```

3\. Open your favorite text editor, copy/paste the code in the snippet below in the text editor. Save the file as _docker-compose.yml_ inside the _~/docker-compose-demo_ directory. The _docker-compose.yml_ stores the configurations for [your application’s services](https://docs.docker.com/compose/).

In the snippet code below:

*   `mysql:5.7` is the base image that Docker Compose pulls and creates a new container.
*   `MYSQL_ROOT_PASSWORD`, `MYSQL_ALLOW_EMPTY_PASSWORD`, and `MYSQL_RANDOM_ROOT_PASSWORD`are three different environments variables within the Docker Compose file. Each environment variable is declared with its values. The value the environment variable gets comes after the`:` symbol.
*   `mysql` service will create the container named `mysql`.

```bash
# Version of Docker compose file
version: "2.2"

services:
# Defining the service
  mysql:
# Defining the base image to be used 
    image: mysql:5.7
    hostname: mysql
    container_name: mysql
# Defining the environmental variable
    environment:
      # ENVIRONMET_VARIABLE_NAME: "environment variable value" 
      MYSQL_ROOT_PASSWORD: "root_password"
      MYSQL_ALLOW_EMPTY_PASSWORD: "password"
      MYSQL_RANDOM_ROOT_PASSWORD: "password"
```

Some containers rely on environment variables to work properly. The one in the example, MySQL, is one of these containers. If you don’t declare the environment variables the container is expecting, it will throw an error. You can see the error below.

![MySQL will throw an error if the environment variables are missing](https://adamtheautomator.com/wp-content/uploads/2021/09/image-106.png)

MySQL will throw an error if the environment variables are missing

4\. Next, execute the `docker-compose up` command. The [`docker-compose up`](https://docs.docker.com/engine/reference/commandline/compose_up/) command reads the YAML file (_docker-compose.yml_) created in the previous step and creates the container. The [`docker-compose up`](https://docs.docker.com/engine/reference/commandline/compose_up/) command starts all the services configured in the Docker Compose file.

5\. Now, verify if all three environment variables are present in the container by running the `docker exec` command and the `env` command.

Running the [docker exec](https://docs.docker.com/engine/reference/commandline/exec/) command will allow you to log in to the container. Running `env` will print the list of the current environment variables with their respective values.

```bash
# ee8a... is the container
docker exec -it ee8af8bfcd41 /bin/bash
```

![The values of the environment variables are taken directly from the docker-compose.yml file you set earlier](https://adamtheautomator.com/wp-content/uploads/2021/09/image-107.png)

The values of the environment variables are taken directly from the docker-compose.yml file you set earlier

## Substituting the Environment Variables

In the previous section, you learned how to declare the environment variables directly within the Docker Compose file by hard coding them. Such an approach is not optimal if you need to secure your credentials. As an alternative, store the values for environment variables in a file named _.env_ that only the admin can read.

Let’s practice using substitution for environment variables. In your terminal:

1\. Create a file named _.env_ in the same ~/_docker-compose-demo_ directory and copy the code below in the _.env_ file. The file will have all the environment variables with their respective values.

```bash
 # Defining the values of environmental variables
 MYSQL_ROOT_PASSWORD="root_password"
 MYSQL_ALLOW_EMPTY_PASSWORD="password"
 MYSQL_RANDOM_ROOT_PASSWORD="password"
```

2\. Next, edit the permissions of the _.env_ file you created in the previous step using the [setfacl](https://docs.oracle.com/cd/E86824_01/html/E54763/setfacl-1.html) command. The command below ensures that the root user has read/write permissions to the _.env_ file.

*   `m` parameter allows you to set the permissions to the files/folders.
*   `u` is the user (`root`) which will have permissions granted to the specified file `~/*docker-compose-demo/.env`

```bash
setfacl -m "u:root:rw" ~/docker-compose-demo/.env
```

3\. Next, edit open the _docker-compose.yml file_ with your favorite editor and comment out the environment section in the _docker-compose.yml_ from the previous section. Add the code below to set default values for the environment variables in the Compose file.

Docker sets the values via the command line or by reading files, such as the _.env_ file in the example. In either case, Docker replaces the values accordingly.

```bash
# Defining the environmental variable using Hardcoded values in variables
    environment:
	    ###  Static way ###
      # MYSQL_ROOT_PASSWORD: "root_password" 
			# MYSQL_ALLOW_EMPTY_PASSWORD: "password"
      # MYSQL_RANDOM_ROOT_PASSWORD: "password"

			### Substitution ### 
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} 
			MYSQL_ALLOW_EMPTY_PASSWORD: ${MYSQL_ALLOW_EMPTY_PASSWORD} 
			MYSQL_RANDOM_ROOT_PASSWORD:  ${MYSQL_RANDOM_ROOT_PASSWORD} 
```

> _The code defines the variables by applying the [string interpolation](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) method. Variables with string interpolation are declared as ${variable}. Docker sets the values of the environment variables at run time._

4\. Again, execute the `docker-compose up` command. When you run the `docker-compose up` command, the _docker-compose.yml_ file looks for the values of the environment variables in the _.env_ file. The `docker-compose` command automatically looks for a _.env_ file in the project directory or in the parent folder of your compose file.

As soon as `docker-compose` finds the value for the environment variables set in _docker-compose.yml_ in the _.env_ file, Compose substitutes the values accordingly and starts the service. Staring the service creates the container defined in the _docker-compose.yml_ file.

## Using Multiple Environment Variables Files for Multiple Environments

Up to now, you have learned two approaches to declare the environment variables. The first one is to declare environment variables within the _docker-compose.yml_ file. The second approach is declaring the environment variables within a single ._env_ file and applying substitution.

Both approaches are suitable when working with a single environment. If you have multiple environments, like Production and/or Testing, you need a different approach. Let’s check out how to create multiple _.env_ files with different names to match your environments!

The example below will emulate the usual environments one might encounter in IT Ops: Dev, QA, and Prod. Back on your terminal:

1\. Navigate to your _~/docker-compose-demo_ directory and create a ._env.dev_ file. Copy/paste the content of the snippet code below in the file and save it. This file will hold the settings use for your MySQL development environment database.

```bash
# Enviornmental Variables file .env.dev
MYSQL_ROOT_PASSWORD="password_DEV"
MYSQL_ALLOW_EMPTY_PASSWORD="password1"
MYSQL_RANDOM_ROOT_PASSWORD="password1"
```

2\. On the same directory, create a _.env.qa_ file and save the contents of the snippet code below in the file. These are the settings for your MySQL quality assurance environment database.

```bash
# Enviornmental Variables  file .env.qa
MYSQL_ROOT_PASSWORD="password_QA"
MYSQL_ALLOW_EMPTY_PASSWORD="password2"
MYSQL_RANDOM_ROOT_PASSWORD="password2"
```

3\. Now create a ._env.prod_ file to store the settings for the hypothetical MySQL production environment database. The contents are below:

```bash
# Enviornmental Variables file .env.prod
MYSQL_ROOT_PASSWORD="password_PROD"
MYSQL_ALLOW_EMPTY_PASSWORD="password3"
MYSQL_RANDOM_ROOT_PASSWORD="password3"
```

4\. Next, execute the `docker-compose` command with the `--env-file` option, specifying the _.env.dev_ file. The `docker-compose` command looks for the _.env.dev_ file in the current ~/_docker-compose-demo_ directory.

```bash
docker-compose --env-file .env.dev up
```

> _Passing the file as an argument allows you to store the file anywhere and with an appropriate name._

Related:[Use Docker Stop Containers Without Screwing Things Up!](https://adamtheautomator.com/docker-stop-containers/)

As you can see below, you can easily pick the different environment files and deploy them by replacing the _.env.dev_ file to either the _.env.qa_ or the _.env.prod_ file.

```bash
# Running the docker-compose command with the QA file
docker-compose --env-file .env.qa up
# Running the docker-compose command with the Prod file
docker-compose --env-file .env.prod up
```

5\. Now, verify if the configuration file (_.env.dev_) has been successfully read by running the `docker exec` command. Running the [docker exec](https://docs.docker.com/engine/reference/commandline/exec/) command will allow you to log in to the container. Running `env` will print the list of the current environment variables.

Notice that all three environment variables (`MYSQL_ROOT_PASSWORD`, `MYSQL_ALLOW_EMPTY_PASSWORD`, and `MYSQL_RANDOM_ROOT_PASSWORD`) are present in the container. Notice that their values come from the _env.dev_ file.

![Logging into the container using the docker exec command with the .env.dev file](https://adamtheautomator.com/wp-content/uploads/2021/09/image-108.png)

Logging into the container using the docker exec command with the _.env.dev_ file

## Incorporating the `env_file` in the Docker Compose File

In the previous section, you saw how to declare the environment variables in ._env_ files. When you store environment variables values in the ._env_ file separately, you end up with lots of lines and references in the _docker-compose.yml_.

To reduce the references and the number of lines for environment variables in the _docker-compose.yml_ file, consider incorporating the [env\_file](https://docs.docker.com/compose/environment-variables/#using-the---env-file--option) in your _docker-compose.yml_ file.

Let’s learn how to incorporate the `env_file` in the Docker compose file. Once again, in the terminal:

1\. Create a file named _var.env_ to hold the settings for your MySQL database. Copy/paste the following into the _var.env_ file and save it to the same _~/docker-compose-demo_ directory.

```bash
MYSQL_ROOT_PASSWORD="password_NEW"
MYSQL_ALLOW_EMPTY_PASSWORD="password_NEW"
MYSQL_RANDOM_ROOT_PASSWORD="password_NEW"
```

2\. Next, open the previously created _docker-compose.yml file_ using your favorite editor. Replace the environment section from the _docker-compose.yml_ that you created previously with `env_file`, and add the file’s path with `- ./var.env`.

Docker now looks for the _./var.env_ file in the same _~/docker-compose-demo_ directory.

```bash
version: "2.2"

services:
  mysql_svc:
    image: mysql:5.7
    hostname: mysql
    container_name: mysql
# Replacing the environment: with env_file: 
  # environment:
  #   MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
  #   MYSQL_ALLOW_EMPTY_PASSWORD: ${MYSQL_ALLOW_EMPTY_PASSWORD}
  #   MYSQL_RANDOM_ROOT_PASSWORD: ${MYSQL_RANDOM_ROOT_PASSWORD}
    env_file:
     - ./var.env
```

Notice that all of the three settings and references are now gone. You are left with a single reference. It may not seem like much in the example. But in the real world, the number of references can get out of hand real quick.

3\. Next, execute the `docker-compose` command. The command looks for the values of the environment variable present in the _var.env_ file and creates the container you defined in the _docker-compose.yml_ file.

![Running docker-compose starts the service. ](https://adamtheautomator.com/wp-content/uploads/2021/09/image-109.png)

Running `docker-compose` starts the service.

Docker creates the services, meaning that the Docker found the values for the environment variables in the _var.env_ file. To confirm, run the `docker exec` and the `env` commands one last time. You will see all the environment variables (`MYSQL_ROOT_PASSWORD`, `MYSQL_ALLOW_EMPTY_PASSWORD`, and `MYSQL_RANDOM_ROOT_PASSWORD`) and their values in the container.

## Conclusion

In this tutorial, you learned different ways of declaring environment variables with Docker compose. The article showed you the great flexibility Docker allows in declaring the environment variables by either coding them directly or using them with separate files.

So which approach are you going to use next while running your Docker containers from Docker Compose?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fdocker-compose-environment-variables%2F&text=Taking%20Advantage%20of%20the%20docker-compose%20Environment%20Variables)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fdocker-compose-environment-variables%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fdocker-compose-environment-variables%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2023/12/buildah.jpg)

### [Building OCI Images with Buildah](/buildah/)

Master the art of crafting OCI images with buildah for seamless containerization—flexible, efficient, and tailored to your container needs.

![](https://adamtheautomator.com/wp-content/uploads/2023/06/docker-raspberry-pi.jpg)

### [How to Install Docker on Raspberry Pi 4](/docker-on-raspberry-pi/)

Excerpt: Learn how to get started with installing Docker on Raspberry Pi 4 and offload development to a small flexible system.

![](https://adamtheautomator.com/wp-content/uploads/2022/09/Getting-Started-with-Docker-Rancher-Desktop.jpg)

### [Getting Started with Docker Rancher Desktop](/docker-rancher/)

Learn how to get started with the Docker Desktop alternative, Docker Rancher Desktop in this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
