Entourloupe
Entourloupe

Reputation: 43

Docker compose change the default environment variables file

In docker-compose.yml I'm trying to change the file which contains the environment variables to .env.local file but nothing works. The values are still thoses from .env file. I'm following this doc: https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option here is my docker-compose.yml file:

version: '3'

services:
    mysqldb:
        image: mysql:5.7
        container_name: project_mysql
        volumes:
          - mysql:/var/lib/mysql
        env_file:
          - .env.local
        environment:
          MYSQL_DATABASE: ${MYSQL_DATABASE}
          MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
          TZ: "Europe/Berlin"
        ports:
            - "3306:3306/tcp"

I also tried to change the name from the file to .env.local.env, .local.env or .variables.env but nothing new happened. I also clear the caches with

docker kill $(docker ps -q)
docker_clean_ps
docker rmi $(docker images -a -q)

but the problem is still here. And there is no error message or code

I have no idea about what's going wrong. Can anybody help me ?

Upvotes: 4

Views: 2522

Answers (2)

Slacky
Slacky

Reputation: 147

Based on the answer provided by @Michael B. I am providing the adapted compose file of the inquiry:

version: '3'

services:
    mysqldb:
        image: mysql:5.7
        container_name: project_mysql
        volumes:
          - mysql:/var/lib/mysql
        env_file:
          - ./local.env
        environment:
          TZ: "Europe/Berlin"
        ports:
            - "3306:3306/tcp"

Note the removal of the MYSQL_DATABASE and MYSQL_ROOT_PASSWORD entries from the environment dictionary due to the fact that based on documentation these would take precedence over the entries defined in the custom env_file.

Upvotes: 1

Mickael B.
Mickael B.

Reputation: 5215

TL; DR: You have a problem of precedence. Don't redefine variables from .env.local with the environment key.


The documentation on env_file says:

Environment variables declared in the environment section override these values – this holds true even if those values are empty or undefined.

The priority for precedence with the .env is

  1. Compose file
  2. Shell environment variables
  3. Environment file
  4. Dockerfile
  5. Variable is not defined
env_file:
  - .env.local
environment:
  MYSQL_DATABASE: ${MYSQL_DATABASE} # Takes precedence over .env.local
  MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} # Takes precedence over .env.local
  TZ: "Europe/Berlin" # Takes precedence over .env.local

Note that using the env_file key will set all the variables from that file, whereas with the environment key you have more control on what variable you want to set.

Upvotes: 3

Related Questions