Multiple docker compose files, with env_file speci

2020-06-24 08:17发布

问题:

I'm working on a project where I'm using docker to create a base configuration, and extending it. My base docker-compose.yml file has links, so I can't use the extends param in the extending compose file. Instead, I'm specifying multiple docker-compose files to the docker-compose tool.

This is working well, except that it seems that the path to the .env file is always relative to the first docker-compose.yml file specified, which breaks my intended functionality.

Example:

docker-compose.yml (lives in a common location, let's say ~/base-app)

web:
  build: .
  volumes:
    - .:/usr/src/app
  ports:
    - "80:3000"
  links:
    - redis
redis:
  image: redis:latest
  ports:
    - "6379:6379"

Now in a child app, I'd like to specify a command and env_file:

docker-compose.override.yml

web:
  environment:
    NODE_ENV: development
  env_file: .env
  command: node server.js

When I run this setup, I'd use the following command:

docker-compose -f ~/base-app/docker-compose.yml -f docker-compose.override.yml up

This works well, as long as I don't specify an env_file. But with the env_file specified, I'll get an error like:

ERROR: Couldn't find env file: ~/base-app/.env

Reading the docker-compose docs, it says that the env file path is relative to the docker-compose file when using the -f flag.

Am I missing something, or is this a bug? What would be a clean way of using an .env file relative to an override docker-compose file?

回答1:

Personally what worked for me and am quiet happy is i have an empty docker-compose file at the root of all my projects that I need to cross reference between, and always set that as the first -f in all compose commands, and have changed all my compose files to use paths relative from the root of my solution/source where the first compose file lives.

/src <- root
/src/docker-compose.yml <- empty docker-compose file only specifying version
/src/api/docker-compose.yml <- docker-compose file using paths relative from /src/
/src/web/docker-compose.yml <- docker-compose file using paths relative from /src/

I then have some batch/powershell files that invoke docker-compose such as:

/** docker-compose-re-up.bat **/
docker-compose -f ../docker-compose.yml -f docker-compose.yml down
docker-compose -f ../docker-compose.yml -f docker-compose.yml build
docker-compose -f ../docker-compose.yml -f docker-compose.yml up -d