liveBook · Manning

.env file

As explained in Learn Docker in a Month of Lunches, Second Edition

An environment file is a file containing environment-specific variable assignments for application configuration.

When a Docker Compose application has separate development and test configurations, repeating filenames, a project name, and port settings on every command gets tedious. A `.env` file in the current directory supplies default environment variables before Compose runs. section 10.3

Listing 10.6 An environment file for Docker Compose
# container configuration - ports to publish:
TODO_WEB_PORT=8877
TODO_DB_PORT=5432

# compose configuration - files and project name:
COMPOSE_PATH_SEPARATOR=;
COMPOSE_FILE=docker-compose.yml;docker-compose-test.yml
COMPOSE_PROJECT_NAME=todo-ch10

This `.env` file sets published-port variables and tells Compose which files and project name to use. Its `COMPOSE_FILE` value selects the core file plus the test override. section 10.3

Start the default test environment

From the configured application's directory, run `docker compose up -d`. With the shown `.env` file present, Compose uses the test override without additional `-f` or `-p` arguments. It creates both web and database containers, even though the core Compose file does not define the database service. section 10.3

A Compose file can also substitute these variables into service settings: `"${TODO_WEB_PORT}:8080"` uses the port supplied by `.env`. Do not confuse this automatic `.env` lookup with a service's `env_file:` entry, which names a file used for container application settings. section 10.3

Change the defaults to select another Compose configuration while keeping the same application image. Named application files such as `appsettings.Test.json` are a different approach: the application selects one through an environment name rather than Compose treating it as its `.env` file. section 10.5 section 18.2

How Learn Docker in a Month of Lunches, Second Edition covers it

How deep it goes
Shows a complete `.env` example and a startup command, but does not detail environment-variable precedence.
Examples
Uses a to-do application whose `.env` selects a test override, sets ports, and starts web and database containers.
What it assumes
Assumes familiarity with running Docker Compose, while showing the variables needed to select its files and project name.
What you can do after
Operate/configure it by placing `.env` beside Compose files and running `docker compose up -d` with fewer command arguments.
How it connects
Connects Docker Compose variable substitution, override files, project names, published ports, and container configuration.

Also explained in

Compare how 4 books explain .env file →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Docker in a Month of Lunches, Second Edition. The section links point to the parts of the book it draws on.