Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to declare env_file explicitely in docker-compose.yml?

I extended the Wordpress image to add XDebug, PHPUnit, composer & phpcs.

My project root looks like this:

docker-wordpress
    Dockerfile
docker-compose.yml
.env

docker-compose.yml:

version: '3.7'

services:
   db:
     image: mysql:5.7
     volumes:
       - ./docker-mysql/db_data:/var/lib/mysql
     restart: always
     ports:
       - "3306:3306"
     env_file: .env

   wordpress:
     depends_on:
       - db
     image: progonkpa/mywordpress
     ports:
       - "80:80"
       - "443:443"
     restart: always
     volumes:
       - ./src:/var/www/html
     env_file: .env

volumes:
    db_data:

This configuration works but only because I added the env_file declaration explicitely while I thought that Docker picks up the file automatically if I followed the right conventions: .env file in root.

I actually want to remove the env_file declarations in docker-compose.yml but then I run into some issues.

MySQL container logs:

database is uninitialized and password option is not specified
You need to specify one of MYSQL_ROOT_PASSWORD

I seems that on first run when the containers are initialized, my variables related to mysql don't come through. The .env file holds the usual Wordpress and MySQL variables:

MYSQL_DATABASE=wordpress
MYSQL_USER=wordpress
MYSQL_PASSWORD=wordpress
MYSQL_ROOT_PASSWORD=wordpress
WORDPRESS_DB_HOST=db:3306
WORDPRESS_DB_USER=wordpress
WORDPRESS_DB_PASSWORD=wordpress

So why is it that my variables don't reach my container?

like image 893
progonkpa Avatar asked Sep 06 '25 20:09

progonkpa


1 Answers

There are two places you can use variables here: inside the compose file itself, and inside the containers created bydocker-compose.

The .env file will be used by docker-compose to adjust the environment of the docker-compose command itself. This is useful for variable inside the yaml file that need to be expanded, or variables used by compose itself. For more on the latter, see the compose CLI variables docs.

Defining an env_file inside the yaml will take environment variables from the file and inject them into the container. That makes it visible to your application, but cannot be used for variables inside your yaml that you want docker-compose to expand since that variable expansion happens before the env_file contents are parsed.

like image 81
BMitch Avatar answered Sep 08 '25 11:09

BMitch