简体   繁体   中英

How to use environment variables with docker-compose from other directory

I'm setting up a new docker-based server and I'm writing a script to run

$ docker-compose

for all my docker-compose.yml files at once.

I know about existence of .env files and I know about env_file option in docker-compose.yml , however the .env files are ignored when I launch

$ docker-compose up

from other directory and not even full path in env_file helps.

my_script.sh:

#!/bin/bash

docker-compose up -f /server1/docker-compose.yml -f /server2/docker-compose.yml -f /server3/docker-compose.yml

Docker-compose.yml:

version: '3'

services:
  service_name:
    build: /server1/apache
    env_file: /server1/.env
    volumes:
      - /web/${ROOT_DOMAIN}/web/:/var/www/:rw

.env

ROOT_DOMAIN=server1.domain.tld

I want to replace the ${ROOT_DOMAIN} variable in volumes for the variable defined in .env file. This works like a charm, when I run

$ docker-compose up

from the /server1/ folder. However when I run my script, which is in other directory, the enviroment variables are ignored and default to null.

How to fix this?

Sorry to say, but this cannot be fixed. The provided .env file must be in the same directory.

This is a requirement of docker compose and is described in the docs (first paragraph): https://docs.docker.com/compose/env-file/

You can roll your own:

function execute() {    
    (set -a;  source .env;  cat $1 | envsubst | kubectl apply -f -)
}

execute foo.yaml

And

$ cat .env
FOO=123
BAR=abc

$ cat foo.yaml
{
    "myfoo": $FOO,
    "mybar": $BAR
}

You can use the flag --env-file to set the path where the .env file is located, example:

docker-compose --env-file ./config/.env.dev up

https://docs.docker.com/compose/environment-variables/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM