Skip to content

How to give good .env

  • by

Now that I’m running my wordpress installation using docker-compose, I found that it’s sometimes convenient to use an .env file to hold all the environment variables for a database container. Not to be confused with the env_file declaration an .env file will be picked up by docker-compose when placed in the same directory as the docker-compose.yml file, that’s all that is needed to apply it. Let’s say we have a Mariadb container in our compose file. We can declare the environment variables as below.

services:
  mariadb:
    image: library/mariadb:latest
    volumes:
      - db_data:/var/lib/mysql/
    restart: always
    environment:
      - MYSQL_DATABASE=${DATABASE}
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_USER=${DB_USER}
      - MYSQL_PASSWORD=${PASSWORD}

Each of the above named variables ${DATABASE}, ${DB_USER} etc will be declared in our .env file.

DATABASE=<wordpress_database_name>
ROOT_PASSWORD=<root_password_for_mariadb>
DB_USER=<wordpress_db_user>
PASSWORD=<wordpress_db_password>

It’s worth pointing out that sometimes there are default environmental variables declared elsewhere that may conflict if you use the same variable nomenclature. To avoid any conflicts you can run docker-compose config before running docker-compose up – this will show you the .env variables that will be applied to the docker-compose file before run time. You can then troubleshoot any issues and apply a sanity check before actually creating your containers.