将环境variables传递到通过组合yaml构build的docker文件中

我正在通过运行命令docker-compose build来调用docker文件,通过我的docker撰写文件。 我在.env文件中定义了我的环境variables。 当我做这个构build时,在我的docker文件中,除了这一行,所有东西都可以工作

RUN git config --global user.email ${USER_NAME} 

它与消息失败

 ←[31mERROR←[0m: Service 'git' failed to build: The command '/bin/sh -c git confi g --global user.email ${USER_NAME}' returned a non-zero code: 1 

但是,如果在容器加载期间(docker-up)加载$ {USER_NAME},则可以正确输出该variables。

 ENTRYPOINT echo ${USER_NAME}//this works 

在docker文件的run命令中传递环境variables的正确方法是什么?

更新:这是一个精简版的文件

yaml文件

 version: '2' services: git: build: context: ./git args: - USER_NAME env_file: - ./common.env 

Env文件

 USER_NAME="My test user" 

Docker文件:

 FROM xxx ARG USER_NAME RUN git config --global user.name ${USER_NAME} ENTRYPOINT git config --list 

命令构build:

 docker-compose build git 

跑:

 docker-compose up git 

生成失败,错误

 RUN git config --global user.name ${USER_NAME} ---> Running in 7b67ddeae989 ←[31mERROR←[0m: Service 'git' failed to build: The command '/bin/sh -c git config --global user.name ${USER_NAME}' returned a non-zero code: 1 

.env适用于docker-compose.yml。 假设你正在构build一个Dockerfile(例如docker docker-compose build ),那么你可以通过构build一个ARG来构build这个variables来构buildRUN

泊坞窗,compose.yml:

 ... build: args: USER_NAME: ${USER_NAME} 

Dockerfile:

 ... ARG USER_NAME=developer747 RUN git config --global user.email ${USER_NAME} 

下面是我的实验中的一个例子:

 $ cat docker-compose.build-arg.yml version: '2' services: build-test: build: args: USER_NAME: ${USER_NAME} context: . dockerfile: df.build-arg image: test-build-args $ cat .env ENV=default USER_NAME=test2 $ cat df.build-arg FROM busybox ARG USER_NAME=default RUN adduser --disabled-password ${USER_NAME} CMD tail -f /dev/null $ docker-compose -f docker-compose.build-arg.yml up --build -d Building build-test Step 1 : FROM busybox ---> 2b8fd9751c4c Step 2 : ARG USER_NAME=default ---> Using cache ---> 9be5b562c784 Step 3 : RUN adduser --disabled-password ${USER_NAME} ---> Using cache ---> bcbaf683e3cf Step 4 : CMD tail -f /dev/null ---> Running in 66908e4f7a0c ---> 06b9774253c2 Removing intermediate container 66908e4f7a0c Successfully built 06b9774253c2 Recreating test_build-test_1 $ docker exec -it test_build-test_1 /bin/sh / # tail /etc/passwd root:x:0:0:root:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/false bin:x:2:2:bin:/bin:/bin/false sys:x:3:3:sys:/dev:/bin/false sync:x:4:100:sync:/bin:/bin/sync mail:x:8:8:mail:/var/spool/mail:/bin/false www-data:x:33:33:www-data:/var/www:/bin/false operator:x:37:37:Operator:/var:/bin/false nobody:x:99:99:nobody:/home:/bin/false test2:x:1000:1000:Linux User,,,:/home/test2:/bin/sh / # exit 
 ENV USER_NAME developer747 RUN git config --global user.email ${USER_NAME} 

请参阅: 环境更换¶