DEV Community

Cover image for Docker Compose to load environment variables
Uzeyr OZ
Uzeyr OZ

Posted on • Edited on

Docker Compose to load environment variables

Docker Compose is a powerful tool for managing and running multiple Docker containers. It allows you to define your application's services, networks, and volumes in a single "docker-compose.yml" file, and then start and stop all of the services with a single command.

One of the key features of Docker Compose is the ability to set environment variables for the services defined in the compose file. Environment variables are key-value pairs that can be used to configure the behavior of a service, such as setting a database connection string or specifying a particular version of an application.

To set environment variables in a Docker Compose file, you can use the "environment" key in the service configuration. This key accepts a list of key-value pairs, where each key is the name of the environment variable and the value is the value to set. For example, to set the "POSTGRES_USER" and "POSTGRES_PASSWORD" environment variables for a PostgreSQL service, you could use the following configuration:

services:
  postgres:
    image: postgres
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword

Enter fullscreen mode Exit fullscreen mode

You can also set environment variables using a .env file, which contains a list of key-value pairs, one per line. To use a .env file with Docker Compose, you need to specify the file in the "env_file" key in the "docker-compose.yml" file. For example:

services:
  postgres:
    image: postgres
    env_file:
      - .env

Enter fullscreen mode Exit fullscreen mode

This tells Docker Compose to load environment variables from a file named ".env" in the same directory as the compose file.

In addition to setting environment variables in the compose file, you can also pass environment variables to the "docker-compose up" command using the "-e" or "--env-file" option. For example, to set the "POSTGRES_USER" variable to "myuser" when starting the services, you could use the following command:

docker-compose up -e POSTGRES_USER=myuser
You can also pass a .env file to the docker-compose command by using the --env-file option like this:

Enter fullscreen mode Exit fullscreen mode
docker-compose  --env-file .env up

Enter fullscreen mode Exit fullscreen mode

In summary, Docker Compose allows you to set environment variables for services in a variety of ways: in the compose file, in a separate .env file, and at runtime using command-line options. This flexibility allows you to easily configure and manage your application's services, making it a powerful tool for development and production environments

Top comments (0)