How to define build-args in docker-compose?

筅森魡賤 提交于 2020-06-24 08:10:31

问题


I have the following docker-compose file

version: '3'
services:
    node1:
            build: node1
            image: node1
            container_name: node1

    node2:
            build: node2
            image: node2
            container_name: node2

I can build both images and start them with a single command

docker-compose up -d --build

But I would like to use build-args on the builds. The original build script of the image outside of the scope of compose looks something like this

#!/bin/sh
docker build \
--build-arg ADMIN_USERNNAME_1=weblogic \
--build-arg ADMIN_PASSWORD_1=weblogic1 \
--build-arg ADMIN_NAME_1=admin \
--build-arg ...
--build-arg ... \
-t test/foo .

Both images would use build-args of the same name but different value. Also, as there are dozens of build args, it would be convenient to store them in a compose service specific build-properties file. Is this possible with docker-compose?


回答1:


You can specify the arguments directly in your docker-compose file:

node1:
    build: node1
        args:
            ADMIN_USERNNAME: weblogic1
            ADMIN_PASSWORD: weblogic1
            ADMIN_NAME: admin1
    image: node1
    container_name: node1

See the official docs for details.




回答2:


You can define your args with your build command of docker-compose.

Example Dockerfile:

FROM nginx:1.13

RUN apt-get -y update && apt-get install -y \
    apache2-utils && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

ARG username
ARG password

RUN htpasswd -bc /etc/nginx/.htpasswd $username $password

docker-compose file:

version: '3'
services:
  node1:
     build: ./dir

The ./dir contains the Dockerfile and I build with this command:

docker-compose build --build-arg username="my-user" --build-arg password="my-pass"

I see already:

Step 5/5 : RUN htpasswd -bc /etc/nginx/.htpasswd $username $password
 ---> Running in 80735195e35d
Adding password for user my-user
 ---> c52c92556825

I bring my stack up:

docker-compose up -d

Now I can check inside the nginx container and my username and (encrypted) password are there:

docker@default:~/test$ docker exec -it test_node1_1 bash
root@208e4d75e2bd:/# cat /etc/nginx/.htpasswd
my-user:$apr1$qg4I/5RO$KMaOPvjbnKdZH37z2WYfe1

Using this method your able to pass build args to your docker-compose stack.




回答3:


In your dockerfile:

ARG CERTBOT_TAG=latest
FROM certbot/certbot:${CERTBOT_TAG}

In your docker-compose.yml:

version: '3'
services:
  certbot-dns-namecheap:
    build:
       context: .
       args:                                                                     
         - CERTBOT_TAG=v0.40.1

And you can use @lvthillo solution with '--build-arg'



来源:https://stackoverflow.com/questions/50734271/how-to-define-build-args-in-docker-compose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!