Docker compose .env default with fallback

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 behavior. 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.example}

Now it will by default use .env.example. 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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)