

FROM golang:1.7.3WORKDIR /go/src/github.com/alexellis/href-counter/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 .
FROM alpine:latest RUN apk --no-cache add ca-certificatesWORKDIR /root/COPY app .CMD ["./app"]
build.sh:
#!/bin/shecho Building alexellis2/href-counter:builddocker build --build-arg https_proxy=$https_proxy --build-arg http_proxy=$http_proxy \ -t alexellis2/href-counter:build . -f Dockerfile.builddocker container create --name extract alexellis2/href-counter:build docker container cp extract:/go/src/github.com/alexellis/href-counter/app ./app docker container rm -f extractecho Building alexellis2/href-counter:latestdocker build --no-cache -t alexellis2/href-counter:latest .rm ./app

FROM golang:1.7.3WORKDIR /go/src/github.com/alexellis/href-counter/RUN go get -d -v golang.org/x/net/html COPY app.go .RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .FROM alpine:latest RUN apk --no-cache add ca-certificatesWORKDIR /root/COPY --from=0 /go/src/github.com/alexellis/href-counter/app .CMD ["./app"]
您只需要单个Dockerfile。您也不需要单独的构建脚本。只需运行docker build:
$ docker build -t app:latest .
最终结果是产生与之前相同大小的image,复杂性显著降低。您不需要创建任何中间image,也不需要将任何artifacts提取到本地系统。
它是如何工作的?第二个FROM指令以alpine:latest image为基础开始一个新的构建阶段。
COPY –from = 0行仅将前一阶段的构建文件复制到此新阶段。Go SDK和任何中间层都被遗忘,而不是保存在最终image中。
为多构建阶段命名

FROM golang:1.7.3 as builderWORKDIR /go/src/github.com/alexellis/href-counter/RUN go get -d -v golang.org/x/net/html COPY app.go .RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .FROM alpine:latest RUN apk --no-cache add ca-certificatesWORKDIR /root/COPY --from=builder /go/src/github.com/alexellis/href-counter/app .CMD ["./app"]
停在特定的构建阶段

$ docker build --target builder -t alexellis2/href-counter:latest .
-
调试特定的构建阶段
-
在debug阶段,启用所有调试或工具,而在production阶段尽量精简
-
在testing阶段,您的应用程序将填充测试数据,但在production阶段则使用生产数据

COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf
原文链接:https://wilhelmguo.tk/blog/post/william/Docker构建之多阶段构建