Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 453
Entourloupe Avatar asked Oct 23 '25 15:10

Entourloupe


1 Answers

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.

like image 86
Mickael B. Avatar answered Oct 25 '25 11:10

Mickael B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!