Florian Ludewig
Florian Ludewig

Reputation: 6012

How to specify multiple "env_files" for a docker compose service?

Currently I have setup my service like the following.

version: '3'
services:
  gateway:
    container_name: gateway
    image: node:lts-alpine
    working_dir: /
    volumes:
      - ./package.json:/package.json
      - ./tsconfig.json:/tsconfig.json
      - ./services/gateway:/services/gateway
      - ./packages:/packages
      - ./node_modules:/node_modules
    env_file: .env
    command: yarn run ts-node-dev services/gateway --colors
    ports:
      - 3000:3000

So I have specified one env_file. But now I want to pass multiple .env files.

Unfortunately, the following is not possible:

    env_files:
       - .env.secrets
       - .env.development

Is there any way to pass multiple .env files to one service in docker-compsoe?

Upvotes: 54

Views: 36450

Answers (3)

Alex Misiulia
Alex Misiulia

Reputation: 1810

Starting from version 2.17.0 (right now it is rc.1, but will be 2.17.0 soon) you can specify multiple files as cli params: sudo docker compose --env-file .env --env-file dev.env up

Pros:

  1. You can access key/values inside the docker-compose.yaml.
  2. You don't need to duplicate env_file section in multiple services.

Cons:

  1. More characters in command.
  2. When you invoke commands like sudo docker compose logs you will need to specify --env-file .env --env-file dev.env. Otherwise you will see errors like WARN[0000] The "VAR_NAME" variable is not set. Defaulting to a blank string.

Upvotes: 15

Ahmet Polat
Ahmet Polat

Reputation: 171

Note that, complementary to @conradkleineespel's answer, if an environment variable is defined in multiple .env files listed under env_file, the value found in the last environment file in the list overwrites all prior (tested in a docker-compose file with version: '3.7'.

Upvotes: 17

conradkleinespel
conradkleinespel

Reputation: 7007

You can specify multiple env files on the env_file option (without s).

For instance:

version: '3'

services:
  hello:
    image: alpine
    entrypoint: ["sh"]
    command: ["-c", "env"]
    env_file:
      - a.env
      - b.env

Upvotes: 51

Related Questions