Use environment files outside the directory to provide parameter during build time with docker-compose

I want to create some different kind of Images that are supplied with some config parameters during the build time. Therefore i found on the documentation here that i can use an env_file: in the docker compose like:

env_file:
   - /opt/secrets.env

But this seems to be not available during build time of the image because when i print the ARGs they are empty. Only if i create an .env file in the folder where the docker-compose.yml is located it works.

So my question is: Is there a chance to provide parameters like ARG or ENV inside the Dockerfile from an file located outside of the folder tree?

tree
|---docker-env/
|    |---docker.env
|
|---docker/
     |---docker-compose.yml
     |---image/
           |---Dockerfile

It doesn’t matter if this file is loaded inside the Dockerfile or in the docker-compose file and handed to the Dockerfile during build.

Any suggestions or ideas how to set the Parameters or is my approach wrong? How can parameters be used during build time? I’m bit stuck with this currently.

My current minimal setup is the following:

docker-compose.yml

version: '3'
services:
  default:
    container_name: base
    image: my/base
    build:
      context: image
      args:
        ROOT_PASSWD: $ROOT_PASSWD
    env_file:
      ./../docker-env/docker.env

Dockerfile

# ----------------------------------------------------------------------
# stick to Ubuntu 16.04
FROM phusion/baseimage:0.10.2

# ----------------------------------------------------------------------
# script global definitions

ARG ROOT_PASSWD


RUN echo try $ROOT_PASSWD

docker.env

# docker.env

ROOT_PASSWD=123

When i try to build this image with docker-compose build --no-cache i get the following output:

$ docker-compose build --no-cache
WARNING: The ROOT_PASSWD variable is not set. Defaulting to a blank string.
Building default
Step 1/3 : FROM phusion/baseimage:0.10.2
 ---> 4ca439e72536
Step 2/3 : ARG ROOT_PASSWD
 ---> Running in e3af937c74c2
Removing intermediate container e3af937c74c2
 ---> b4937c9876ec
Step 3/3 : RUN echo try $ROOT_PASSWD
 ---> Running in 1548a0a77100
try
Removing intermediate container 1548a0a77100
 ---> 1802ed0eb009
Successfully built 1802ed0eb009
Successfully tagged my/base:latest

On Step 3/3 there is the “try ” but no output from the ARG.

I hope someone can suggest a hint how to solve this.

Source: StackOverflow