7.1: The .env file: The settings vault

DockerWhen deploying containers, you’ll often need to configure your services: passwords, ports, database names, storage paths, and so on.
Modifying the source code or configuration filesdocker-compose.ymlevery time the environment changes is tedious and risky. That’s where the configuration file.envcomes in!

What is an environment file.env?

  • It is a simple text file containing environment variables in key=value format.
  • Example of a `.env` file.envfor a PHP/MariaDB stack:
# Configuration BDD
DB_HOST=db
DB_PORT=3306
DB_USER=root
DB_PASSWORD=monsecret
DB_NAME=monprojet# Configuration applicative
APP_ENV=development
APP_DEBUG=true
  • These variables are then interpolated into yourdocker-compose.yml using the syntax ${VARIABLE}.

Example in adocker-compose.yml :

services:
db:
image: mariadb:10.11
environment:
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
MYSQL_DATABASE: ${DB_NAME}

php:
image: php:8.2-apache
environment:
APP_ENV: ${APP_ENV}
APP_DEBUG: ${APP_DEBUG}

Advantages of the .env

  1. Portability: the samedocker-compose.yml can run in dev, test, or prod environments simply by changing the .env.
  2. Relative security: secrets are no longer hard-coded in YAML files.
  3. Clarity: centralizes all configuration settings in one place.
  4. Easier maintenance: changing a variable = modifying it in only one place.

Best practices

  • Never commit files.envcontaining secrets to a public repository.
  • Prefer a.env.example to provide a template without the secrets.
  • Use explicit and consistent names for variables.

📌Key takeaway:
The file.envis your settings vault. It allows you to make your stack flexible, portable, and maintainable without touching the code.