DEV Community

Geoffrey Kim
Geoffrey Kim

Posted on

How to Ensure Docker Compose Uses Environment Variables from the `.env` File

When working with Docker Compose, you might encounter a situation where environment variables defined in your .env file are not being picked up correctly. This can be particularly frustrating if you have variables set in your shell that are taking precedence. Here’s a step-by-step guide to ensure Docker Compose uses the environment variables from your .env file.

Understanding Environment Variable Precedence

Docker Compose uses the following order of precedence for environment variables:

  1. Environment variables set in the shell before running docker compose.
  2. Environment variables defined in the docker-compose.yml file.
  3. Environment variables defined in the .env file.

To ensure that the environment variables from the .env file are used, you need to unset any conflicting environment variables in your shell.

Step-by-Step Guide

  1. Unset the Environment Variable in Your Shell:
    Before running Docker Compose, unset any environment variables that might conflict with those in your .env file. For example, if you have BACKEND_CORS_ORIGINS set in your shell, unset it:

    unset BACKEND_CORS_ORIGINS
    
  2. Run Docker Compose with the .env File:
    After unsetting the environment variable, run Docker Compose to build and start your containers:

    docker compose up -d --build
    
  3. Automate the Process with a Script:
    To streamline the process, you can create a script that unsets the environment variables and then runs Docker Compose. Here’s an example script named restart.sh:

    #!/usr/bin/env sh
    set -e
    
    # Unset environment variables that might be set in the shell
    unset BACKEND_CORS_ORIGINS
    
    # Stop and remove existing containers, volumes, and networks
    docker compose down -v --remove-orphans
    
    # Build and start the containers
    docker compose up -d --build
    

    Save this script and run it whenever you update the .env file:

    sh scripts/restart.sh
    
  4. Verify the Environment Variables:
    After starting the containers, you can verify that the environment variables are set correctly inside the running container:

    docker compose exec backend env | grep BACKEND_CORS_ORIGINS
    

Conclusion

By unsetting environment variables in your shell before running Docker Compose, you can ensure that the variables defined in your .env file are used. This approach helps avoid conflicts and ensures that your Docker containers are configured correctly. Automating the process with a script can save time and reduce the risk of errors.

By following these steps, you can avoid common pitfalls and ensure that your Docker Compose environment is set up correctly.

Top comments (0)