且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将环境变量传递到通过Compose Yaml构建的Docker文件中

更新时间:2022-05-31 10:12:06

.env适用于docker-compose.yml.假设您是从compose内部构建Dockerfile(例如, docker-compose build ),则可以将 ARG 从compose传递到构建中,以为build 运行代码>:

The .env applies to the docker-compose.yml. Assuming you are building a Dockerfile from within your compose (e.g. docker-compose build), then you can pass an ARG from compose into the build to provide this variable for build RUN:

docker-compose.yml:

docker-compose.yml:

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

Dockerfile:

Dockerfile:

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


这是我的实验室中的一个示例:


Here's an example of this in my lab:

$ 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