Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Env file is not read when I use docker-compose -f in a different directory

I have a problem with my Docker .env file. When I'm in my Docker folder (where I have the docker-compose.yml and .env file), the environment variables are read from .env fine. However, when I run docker-compose -f ./docker/docker-compose.yml up --build -d in a higher-level directory I get warnings like:

The MYSQL_ROOT_PASSWORD variable is not set. Defaulting to a blank string. 

Has anyone encountered this problem? I tried setting the env_file property in docker-compose.yml and using other file encodings (I found this solution in Google) and still nothing.

This is my config:

version: '2'

services:
    mysql:
        container_name: mysql
        image: mysql
        volumes:
            - "./.data/db:/var/lib/mysql"
        environment:
            MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
            MYSQL_DATABASE: ${MYSQL_DATABASE}
            MYSQL_USER: ${MYSQL_USER}
            MYSQL_PASSWORD: ${MYSQL_PASSWORD}

.env file:

# MySQL
MYSQL_ROOT_PASSWORD=test
MYSQL_DATABASE=test
MYSQL_USER=test
MYSQL_PASSWORD=test
like image 868
jager91 Avatar asked Dec 04 '17 10:12

jager91


People also ask

Can you use environment variables in docker-compose?

Configure Compose using environment variablesSeveral environment variables are available for you to configure the Docker Compose command-line behavior.

Does docker use .env file?

Here's a list of easy takeaways: The . env file, is only used during a pre-processing step when working with docker-compose. yml files.

How do I pass environment variables to docker containers?

Using –env, -e When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.

Where should .env files go?

You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables. The dotenv library reads this. env file and appends it to process.


1 Answers

As Tagc says, this is the documented behavior of docker-compose with a .env file, it must be in the directory where you are running docker-compose. You cannot use env_file for this because that's setting a different environment. The .env file sets the environment used by docker-compose to parse the yml file (and therefore could not be set from within the file, that would be a circular dependency), while the env_file injects environment variables into the running containers.

If you cannot cd into the folder or move your .env file for some reason, you can manually source the file with something like:

env $(cat docker/.env | grep -v ^# | xargs) \
  docker-compose -f docker/docker-compose.yml up --build -d
like image 200
BMitch Avatar answered Sep 30 '22 18:09

BMitch