Docker Env Files

Env Files

Multiple .env files can be used and are read in a specific order.

# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides

.env File Content

The .env file can have any number of vars as key-value pairs.

# Environemnt.
HTTP_HOST="localhost:8080"
APP_ROOT="/var/www/"
APP_WEB_ROOT="/var/www/html/"

# Database.
MYSQL_DATABASE_HOST="db"
MYSQL_DATABASE_NAME="portal"
MYSQL_ROOT_USERNAME="root"
MYSQL_ROOT_PASSWORD="rootpass"
MYSQL_USER_USERNAME="db_user"
MYSQL_USER_PASSWORD="password"

Docker Compose

Load a specific .env file into a container.

services:

  db:
    container_name: db-server
    env_file:
      - ../nrit-visit-app-env/.env
    image: mariadb:11.4.2
    restart: always
    volumes:
      - db-data:/var/lib/mysql
    ports:
      - "3306:3306"

Env files with PHP

Mount an .env file into a container.

services:

  nritweb-php-server:
    container_name: web-server
    build:
      context: .
    depends_on:
      - db
    ports:
      - "8080:80"
    volumes:
      - ../nrit-visit-app-env:/var/www/env

Use composer to install the Symfony Dotenv Component in the PHP project.

// Copmoser autoloader.
require_once('../vendor/autoload.php');

// Symfony Dotenv Component init.
use Symfony\Component\Dotenv\Dotenv;

// Read the .env file.
$dotenv = new Dotenv();
$dotenv->load('../env/.env');

// Use a var.
$db_host = $_ENV['MYSQL_DATABASE_HOST'];