Specify the env file docker compose uses

You can use inheritance for this. If you have one "base" service where you set up the environment, all of your other services can inherit from that.

Example:

version: "2"

services:
  base:
    env_file:
      - my_env.txt

  web:
    extends:
      service: base
    image: foo

  database:
    extends:
      service: base
    image: foo-db

The above example has everything in the same file, but you can also split this up into multiple files, where the base service would reside in a base.yaml file. You just need to add file: base.yaml to the extends section. Please see the documentation here.

I use this approach for setting the proxy variables for all containers. I have a proxy.yaml file that defines a proxy-app service that picks up the proxy environment variables from the shell. All of my real services extend the proxy-app service and thus inherit the environment settings from that service.


According to the documentation, it's now possible to load an environment file (contrary to a per-service file), docker-compose will then export the env variables defined in this env file prior to starting any service, they can then be used in the docker-compose.yml config file itself:

version: "3.7"
services:
  
  node:
    environment:
      APP_ENV: "${APP_ENV}"
      NODE_ENV: "${NODE_ENV}"
    ports:
      - "${HOST_EXPOSED_NODEJS_DEBUG_PORT}:9229"
    volumes:
      - type: bind
        source: ./project
        target: /var/www/project
        read_only: false

Since docker-compose 1.25 it's also possible to specify a custom .env file with the --env-file flag (unfortunately it's currently not possible to specify multiple .env files with the --env-file flag)


The --env-file command-line argument and the env_file docker-compose.yml variable specify the env file to use for the container, not for the container build. To set a different file (e.g. alt.env) for the build itself, use this:

env $(cat alt.env) docker-compose up --build