Docker 多階段構(gòu)建最佳實踐

多階段構(gòu)建出現(xiàn)之前
FROM golang:1.7.3
WORKDIR /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-certificates
WORKDIR /root/
COPY app .
CMD ["./app"]
#!/bin/sh
echo Building alexellis2/href-counter:build
docker build --build-arg https_proxy=$https_proxy --build-arg http_proxy=$http_proxy \
-t alexellis2/href-counter:build . -f Dockerfile.build
docker 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 extract
echo Building alexellis2/href-counter:latest
docker build --no-cache -t alexellis2/href-counter:latest .
rm ./app
多階段構(gòu)建大大簡化了這種情況!
使用多階段構(gòu)建
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 CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
您只需要單個Dockerfile。您也不需要單獨的構(gòu)建腳本。只需運行docker build:
$ docker build -t app:latest .
最終結(jié)果是產(chǎn)生與之前相同大小的image,復(fù)雜性顯著降低。您不需要創(chuàng)建任何中間image,也不需要將任何artifacts提取到本地系統(tǒng)。
為多構(gòu)建階段命名
FROM golang:1.7.3 as builder
WORKDIR /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-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
停在特定的構(gòu)建階段
$ docker build --target builder -t alexellis2/href-counter:latest .
調(diào)試特定的構(gòu)建階段 在debug階段,啟用所有調(diào)試或工具,而在production階段盡量精簡 在testing階段,您的應(yīng)用程序?qū)⑻畛錅y試數(shù)據(jù),但在production階段則使用生產(chǎn)數(shù)據(jù)
使用外部鏡像作為stage
如有必要,Docker會提取image并從那里開始復(fù)制。
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf
鏈接: http://dockone.io/article/8179

往 期 推 薦 1、Intellij IDEA這樣 配置注釋模板,讓你瞬間高出一個逼格! 2、吊炸天的 Docker 圖形化工具 Portainer,必須推薦給你! 3、最牛逼的 Java 日志框架,性能無敵,橫掃所有對手! 4、把Redis當(dāng)作隊列來用,真的合適嗎? 5、驚呆了,Spring Boot居然這么耗內(nèi)存!你知道嗎? 6、全網(wǎng)最全 Java 日志框架適配方案!還有誰不會? 7、Spring中毒太深,離開Spring我居然連最基本的接口都不會寫了

點分享

點收藏

點點贊

點在看
評論
圖片
表情

