我通过运行命令docker-compose build通过我的docker compose文件调用docker文件。我在.env文件中定义了环境变量。当我进行构建时,在我的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-compose up)期间回显$ {USER_NAME},则可以正确打印出该变量。
ENTRYPOINT echo ${USER_NAME}//this works
在docker文件中传递run命令中的环境变量的正确方法是什么?
更新:这是文件的精简版
yaml文件
version: '2'
services:
git:
build:
context: ./git
args:
- USER_NAME
env_file:
- ./common.env
环境文件
USER_NAME="My test user"
Docker文件:
FROM xxx
ARG USER_NAME
RUN git config --global user.name ${USER_NAME}
ENTRYPOINT git config --list
命令 建立:
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
答案 0 :(得分:2)
.env适用于docker-compose.yml。假设您正在构建中构建一个Dockerfile(例如docker-compose build
),那么您可以将一个ARG
从compose传递到构建中,以便为构建RUN
提供此变量:
搬运工-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