Docker compose .env default with fallback

I would like to save a docker-compose.yaml file inside a git repo. I would like to have some default .env variables, but I would like to have also something like .env.local which could override .env, but I don't want to commit .env.local so it should be gitignored.

Is there any way to tell docker-compose.yaml "use .env.local if exists, otherwise .env"?

The idea is to allow someone to clone the repository, use their own .env.local if they want, without having git changes to commit or use default .env values if they don't want to customize it.


Solution 1:

If you are using the values from the env file by name, like below. You can use posix parameter expansion like shown to get default value behaviour. Compose will use the value for that variable from .env file or if it's set in your shell, otherwise it will default to default-value.

services:
  myapp:
    environment:
      SOME_VALUE: ${SOME_VALUE:-default-value}

If you are intending to use it under the key env_file you can use the knowledge from the above example do to some tricks.

services:
  myapp:
    env_file: ${ENV_FILE:-.env.local}

Now it will by default use .env.local. Unless you happen to place a .env file at the root of your project (from where you invoke compose) and overwrite the ENV_FILE variable in there. Or export it in your shell. Note that the .env file must include ENV_FILE=.env in order to expand to .env in env_file:

ENV_FILE=.env
OTHER_STUFF=foo