我可以将Docker Compose与使用构建器模式的图像一起使用吗?

时间:2017-07-17 19:29:39

标签: docker docker-compose

我知道新的multi-stage build功能,它可以很好地与Docker Compose配合使用。但是,让我们说我坚持使用构建器模式(不要问)...有没有办法让docker-compose up使用构建器模式所需的构建脚本?

考虑链接文章中的相同构建器模式文件:

Dockerfile.build

FROM golang:1.7.3
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go .
RUN go get -d -v golang.org/x/net/html \
  && CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

Dockerfile

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY app .
CMD ["./app"]

build.sh

#!/bin/sh
docker build -t alexellis2/href-counter:build . -f Dockerfile.build

docker create --name extract alexellis2/href-counter:build  
docker cp extract:/go/src/github.com/alexellis/href-counter/app ./app  
docker rm -f extract

docker build --no-cache -t alexellis2/href-counter:latest .
rm ./app

我可以构建一个像这样的Docker Compose文件,但我不知道如何cp来自临时Docker容器的文件。

搬运工-compose.yml

version: '3'
services:
  app: 
    build: .
    depends_on:
     - app-build
  app-build:
    build:
      context: .
      dockerfile: Dockerfile.build

我可以构建临时Docker镜像/容器并使用上面的cp脚本的第一部分运行build.sh,然后使用精简的撰写文件,但是,我可能会以及坚持使用剧本。

3 个答案:

答案 0 :(得分:2)

据我了解,您在询问是否可以在撰写文件中使用docker cp之类的内容从临时容器中提取工件。

好吧,使用共享volume是一个选项。

version: '3'
    services:
      app: 
        build: .
        depends_on:
         - app-build
        volumes:
        - shared:/source        
      app-build:
        build:
          context: .
          dockerfile: Dockerfile.build
        volumes:
        - shared:/output
    volumes:
      - shared:

但您必须在app服务中添加一个脚本,该脚本将检查app-build是否已完成其工作并且工件准备就绪。

使用共享卷有点冒险。你必须知道自己在做什么。

  

多个容器还可以共享一个或多个数据卷。但是,写入单个共享卷的多个容器可能会导致数据损坏。   https://docs.docker.com/engine/tutorials/dockervolumes/#important-tips-on-using-shared-volumes

github上有一个名为“将copy添加到yaml配置”的问题:https://github.com/docker/compose/issues/1664

我想在compose文件中有这样的选项。您可以在上面的链接上查看其他人对此的看法。该问题现已结束,但可能会再次开启。

答案 1 :(得分:1)

一种方法可以使用2个docker-compose调用,并结合目录映射:

version: '3'
services:
  app: 
    build: .

  app-build:
    build:
      context: .
      dockerfile: Dockerfile.build
    volumes:
       - ./build/:/go/src/github.com/alexellis/href-counter/

然后:

#This will produce local ./build/app artifact
docker-compose build app-build

#Having the previous artifact, will use it:
docker-compose build app

只需将其更改为Dockerfile:

COPY build/app .

但是,我建议您使用Multi Stage Build方法。比这简单得多。

答案 2 :(得分:0)

Docker compose没有构建依赖关系,这些依赖关系用于确定构建后容器的启动顺序。并且它不允许您创建容器并将文件复制出来以在另一个构建中使用。因此,如果您的环境至少运行17.05,那么您将使用上述构建脚本或使用新的多阶段构建。

相关问题