理解Docker的多階段鏡像構建

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Docker技術從2013年誕生到目前已經4年有餘了。對於已經接納和使用Docker技術在日常開發工作中的開發人員而言,構建Docker鏡像已經是家常便飯。但這是否意味著Docker的image構建機制已經相對完美了呢?不是的,Docker官方依舊在持續最佳化鏡像構建機制。這不,從今年發布的Docker 17.05版本起,Docker開始支援容器鏡像的多階段構建(multi-stage build)了。

什麼是鏡像多階段構建呢?直接給出概念定義太突兀,這裡先賣個關子,我們先從日常開發中用到的鏡像構建的方式和所遇到的鏡像構建的問題說起。

一、同構的鏡像構建

我們在做鏡像構建時的一個常見的情境就是:應用在開發人員自己的開發機或伺服器上直接編譯,編譯出的二進位程式再打入鏡像。這種情況一般要求編譯環境與鏡像所使用的base image是相容的,比如說:我在Ubuntu 14.04上編譯應用,並將應用打入基於ubuntu系列base image的鏡像。這種構建我稱之為“同構的鏡像構建”,因為應用的編譯環境與其部署啟動並執行環境是相容的:我在Ubuntu 14.04下編譯出來的應用,可以基本無縫地在基於ubuntu:14.04及以後版本base image鏡像(比如:16.04、16.10、17.10等)中運行;但在不完全相容的base image中,比如centos中就可能會運行失敗。

1、同構鏡像構建舉例

這裡舉個同構鏡像構建的例子(後續的章節也是基於這個例子的),注意:我們的編譯環境為Ubuntu 16.04 x86_64虛擬機器、Go 1.8.3和docker 17.09.0-ce。

我們用一個Go語言中最常見的http server作為例子:

// github.com/bigwhite/experiments/multi_stage_image_build/isomorphism/httpserver.gopackage mainimport (        "net/http"        "log"        "fmt")func home(w http.ResponseWriter, req *http.Request) {        w.Write([]byte("Welcome to this website!\n"))}func main() {        http.HandleFunc("/", home)        fmt.Println("Webserver start")        fmt.Println("  -> listen on port:1111")        err := http.ListenAndServe(":1111", nil)        if err != nil {                log.Fatal("ListenAndServe:", err)        }}

編譯這個程式:

# go build -o myhttpserver httpserver.go# ./myhttpserverWebserver start  -> listen on port:1111

這個例子看起來很簡單,也沒幾行代碼,但背後Go net/http包在底層做了大量的事情,包括很多系統調用,能夠反映出應用與作業系統的“耦合”,這在後續的講解中會體現出來。接下來我們就來為這個程式構建一個docker image,並基於這個image來啟動一個myhttpserver容器。我們選擇ubuntu:14.04作為base image:

// github.com/bigwhite/experiments/multi_stage_image_build/isomorphism/DockerfileFrom ubuntu:14.04COPY ./myhttpserver /root/myhttpserverRUN chmod +x /root/myhttpserverWORKDIR /rootENTRYPOINT ["/root/myhttpserver"]執行構建:# docker build -t myrepo/myhttpserver:latest .Sending build context to Docker daemon  5.894MBStep 1/5 : FROM ubuntu:14.04 ---> dea1945146b9Step 2/5 : COPY ./myhttpserver /root/myhttpserver ---> 993e5129c081Step 3/5 : RUN chmod +x /root/myhttpserver ---> Running in 104d84838ab2 ---> ebaeca006490Removing intermediate container 104d84838ab2Step 4/5 : WORKDIR /root ---> 7afdc2356149Removing intermediate container 450ccfb09ffdStep 5/5 : ENTRYPOINT /root/myhttpserver ---> Running in 3182766e2a68 ---> 77f315e15f14Removing intermediate container 3182766e2a68Successfully built 77f315e15f14Successfully tagged myrepo/myhttpserver:latest# docker imagesREPOSITORY            TAG                 IMAGE ID            CREATED             SIZEmyrepo/myhttpserver   latest              77f315e15f14        18 seconds ago      200MB# docker run myrepo/myhttpserverWebserver start  -> listen on port:1111

以上是最基本的image build方法。

接下來,我們可能會遇到如下需求:
* 搭建一個Go程式的構建環境有時候是很耗時的,尤其是對那些依賴很多第三方開源包的Go應用來說,下載包就需要很長時間。我們最好將這些易變的東西統統打包到一個用於Go程式構建的builder image中;
* 我們看到上面我們構建出的myrepo/myhttpserver image的SIZE是200MB,這似乎有些過於“龐大”了。雖然每個主機node上的docker有cache image layer的能力,但我們還是希望能build出更加精簡短小的image。

2、藉助golang builder image

Docker Hub上提供了一個帶有go dev環境的官方golang image repository,我們可以直接使用這個golang builder image來輔助構建我們的應用image;對於一些對第三方包依賴較多的Go應用,我們也可以以這個golang image為base image定製我們自己的專用builder image。

我們基於golang:latest這個base image構建我們的golang-builder image,我們編寫一個Dockerfile.build用於build golang-builder image:

// github.com/bigwhite/experiments/multi_stage_image_build/isomorphism/Dockerfile.buildFROM golang:latestWORKDIR /go/srcCOPY httpserver.go .RUN go build -o myhttpserver ./httpserver.go

在同目錄下構建golang-builder image:

# docker build -t myrepo/golang-builder:latest -f Dockerfile.build .Sending build context to Docker daemon  5.895MBStep 1/4 : FROM golang:latest ---> 1a34fad76b34Step 2/4 : WORKDIR /go/src ---> 2361824677d3Removing intermediate container 01d8f4e9f0c4Step 3/4 : COPY httpserver.go . ---> 1ff14bb0bc56Step 4/4 : RUN go build -o myhttpserver ./httpserver.go ---> Running in 37a1b76b7b9e ---> 2ac5347bb923Removing intermediate container 37a1b76b7b9eSuccessfully built 2ac5347bb923Successfully tagged myrepo/golang-builder:latestREPOSITORY              TAG                 IMAGE ID            CREATED             SIZEmyrepo/golang-builder   latest              2ac5347bb923        3 minutes ago       739MB

接下來,我們就基於golang-builder中已經build完畢的myhttpserver來構建我們最終的應用image:

# docker create --name appsource myrepo/golang-builder:latest# docker cp appsource:/go/src/myhttpserver ./# docker rm -f appsource# docker rmi myrepo/golang-builder:latest# docker build -t myrepo/myhttpserver:latest .

這段命令的邏輯就是從基於golang-builder image啟動的容器appsource中將已經構建完畢的myhttpserver拷貝到主機目前的目錄中,然後刪除臨時的container appsource以及上面構建的那個golang-builder image;最後的步驟和第一個例子一樣,基於本地目錄中的已經構建完的myhttpserver構建出最終的image。為了方便,你也可以將這一系列命令放到一個Makefile中去。

3、使用size更小的alpine image

builder image並不能協助我們為最終的應用image“減重”,myhttpserver image的Size依舊停留在200MB。要想“減重”,我們需要更小的base image,我們選擇了alpine。Alpine image的size不到4M,再加上應用的size,最終應用Image的Size估計可以縮減到20M以下。

結合builder image,我們只需將Dockerfile的base image改為alpine:latest:

// github.com/bigwhite/experiments/multi_stage_image_build/isomorphism/Dockerfile.alpineFrom alpine:latestCOPY ./myhttpserver /root/myhttpserverRUN chmod +x /root/myhttpserverWORKDIR /rootENTRYPOINT ["/root/myhttpserver"]

構建alpine版應用image:

# docker build -t myrepo/myhttpserver-alpine:latest -f Dockerfile.alpine .Sending build context to Docker daemon  6.151MBStep 1/5 : FROM alpine:latest ---> 053cde6e8953Step 2/5 : COPY ./myhttpserver /root/myhttpserver ---> ca0527a62d39Step 3/5 : RUN chmod +x /root/myhttpserver ---> Running in 28d0a8a577b2 ---> a3833af97b5eRemoving intermediate container 28d0a8a577b2Step 4/5 : WORKDIR /root ---> 667345b78570Removing intermediate container fa59883e9fdbStep 5/5 : ENTRYPOINT /root/myhttpserver ---> Running in adcb5b976ca3 ---> 582fa2aedc64Removing intermediate container adcb5b976ca3Successfully built 582fa2aedc64Successfully tagged myrepo/myhttpserver-alpine:latest# docker imagesREPOSITORY                   TAG                 IMAGE ID            CREATED             SIZEmyrepo/myhttpserver-alpine   latest              582fa2aedc64        4 minutes ago       16.3MB

16.3MB,Size的確降下來了!我們基於該image啟動一個容器,看應用運行是否有什麼問題:

# docker run myrepo/myhttpserver-alpine:lateststandard_init_linux.go:185: exec user process caused "no such file or directory"

容器啟動失敗了!為什麼呢?因為alpine image並非ubuntu環境的同構image。我們在下面詳細說明。

二、異構的鏡像構建

我們的image builder: myrepo/golang-builder:latest是基於golang:latest這個image。golang base image有兩個模板:Dockerfile-debain.template和Dockerfile-alpine.template。而golang:latest是基於debian模板的,與ubuntu相容。構建出來的myhttpserver對動態共用連結庫的情況如下:

 # ldd myhttpserver    linux-vdso.so.1 =>  (0x00007ffd0c355000)    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007ffa8b36f000)    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffa8afa5000)    /lib64/ld-linux-x86-64.so.2 (0x000055605ea5d000)

debian系的linux distribution使用了glibc。但alpine則不同,alpine使用的是musl libc的實現,因此當我們運行上面的那個容器時,載入器因找不到myhttpserver依賴的libc.so.6而失敗退出。

這種構建環境與運行環境不相容的情況我這裡稱之為“異構的鏡像構建”。那麼如何解決這個問題呢?我們繼續看:

1、靜態構建

在主流程式設計語言中,Go的移植性已經是數一數二的了,尤其是Go 1.5之後,Go將runtime中的C代碼都用Go重寫了,對libc的依賴已經降到最低了,但仍有一些feature提供了兩個版本的實現:C實現和Go實現。並且預設情況下,即在CGO_ENABLED=1的情況下,程式和先行編譯的標準庫都採用了C的實現。關於這方面的詳細論述請參見我之前寫的《也談Go的可移植性》一文,這裡就不贅述了。於是採用了不同libc實現的debian系和alpine系自然存在不相容的情況。要解決這個問題,我們首先考慮對Go程式進行靜態構建,然後將靜態構建後的Go應用放入alpine image中。

我們修改一下Dockerfile.build,在編譯Go源檔案時加上CGO_ENABLED=0:

// github.com/bigwhite/experiments/multi_stage_image_build/heterogeneous/Dockerfile.buildFROM golang:latestWORKDIR /go/srcCOPY httpserver.go .RUN CGO_ENABLED=0 go build -o myhttpserver ./httpserver.go

構建這個builder image:

# docker build -t myrepo/golang-static-builder:latest -f Dockerfile.build .Sending build context to Docker daemon  4.096kBStep 1/4 : FROM golang:latest ---> 1a34fad76b34Step 2/4 : WORKDIR /go/src ---> 593cd9692019Removing intermediate container ee005d487ad5Step 3/4 : COPY httpserver.go . ---> a095eb69e716Step 4/4 : RUN CGO_ENABLED=0 go build -o myhttpserver ./httpserver.go ---> Running in d9f3b3a6c36c ---> c06fe8dccbadRemoving intermediate container d9f3b3a6c36cSuccessfully built c06fe8dccbadSuccessfully tagged myrepo/golang-static-builder:latest# docker imagesREPOSITORY                     TAG                 IMAGE ID            CREATED             SIZEmyrepo/golang-static-builder   latest              c06fe8dccbad        31 seconds ago      739MB

接下來,我們再基於golang-static-builder中已經build完畢的靜態串連的myhttpserver來構建我們最終的應用image:

# docker create --name appsource myrepo/golang-static-builder:latest# docker cp appsource:/go/src/myhttpserver ./# ldd myhttpserver    not a dynamic executable# docker rm -f appsource# docker rmi myrepo/golang-static-builder:latest# docker build -t myrepo/myhttpserver-alpine:latest -f Dockerfile.alpine .

運行新image:

# docker run myrepo/myhttpserver-alpine:latestWebserver start  -> listen on port:1111

Note: 我們可以用strace來證明靜態串連時Go只使用的是Go自己的runtime實現,而並未使用到libc.a中的代碼:

# CGO_ENABLED=0 strace -f go build httpserver.go 2>&1 | grep open | grep -o '/.*\.a'  > go-static-build-strace-file-open.txt

開啟go-static-build-strace-file-open.txt檔案查看檔案內容,你不會找到libc.a這個檔案(在Ubuntu下,一般libc.a躺在/usr/lib/x86_64-linux-gnu/下面),這說明go build根本沒有嘗試去open libc.a檔案並擷取其中的符號定義。

2、使用alpine golang builder

我們的Go應用運行在alpine based的container中,我們可以使用alpine golang builder來構建我們的應用(無需靜態連結)。前面提到過golang有alpine模板:

REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZEgolang                       alpine              9e3f14138abd        7 days ago          269MB

alpine版golang builder的Dockerfile內容如下:

//github.com/bigwhite/experiments/multi_stage_image_build/heterogeneous/Dockerfile.alpine.buildFROM golang:alpineWORKDIR /go/srcCOPY httpserver.go .RUN go build -o myhttpserver ./httpserver.go

後續的操作與前面golang builder的操作並不二致:利用alpine golang builder構建我們的應用,並將其打入alpine image,這裡就不贅述了。

三、多階段鏡像構建:提升開發人員體驗

在Docker 17.05以前,我們都是像上面那樣構建鏡像的。你會發現即便採用異構image builder模式,我們也要維護兩個Dockerfile,並且還要在docker build命令之外執行一些諸如從容器內copy應用程式、清理build container和build image等的操作。Docker社區看到了這個問題,於是實現了多階段鏡像構建機制(multi-stage)。

我們先來看一下針對上面例子,multi-stage build所使用Dockerfile:

//github.com/bigwhite/experiments/multi_stage_image_build/multi_stages/DockerfileFROM golang:alpine as builderWORKDIR /go/srcCOPY httpserver.go .RUN go build -o myhttpserver ./httpserver.goFrom alpine:latestWORKDIR /root/COPY --from=builder /go/src/myhttpserver .RUN chmod +x /root/myhttpserverENTRYPOINT ["/root/myhttpserver"]

看完這個Dockerfile的內容,你的第一趕腳是不是把之前的兩個Dockerfile合并在一塊兒了,每個Dockerfile單獨作為一個“階段”!事實也是這樣,但這個Docker也多了一些新的文法形式,用於建立各個“階段”之間的聯絡。針對這樣一個Dockerfile,我們應該知道以下幾點:

  • 支援Multi-stage build的Dockerfile在以往的多個build階段之間建立內在串連,讓後一個階段構建可以使用前一個階段構建的產物,形成一條構建階段的chain;
  • Multi-stages build的最終結果僅產生一個image,避免產生冗餘的多個臨時images或臨時容器物件,這正是我們所需要的:我們只要結果。

我們來使用multi-stage來build一下上述例子:

# docker build -t myrepo/myhttserver-multi-stage:latest .Sending build context to Docker daemon  3.072kBStep 1/9 : FROM golang:alpine as builder ---> 9e3f14138abdStep 2/9 : WORKDIR /go/src ---> Using cache ---> 7a99431d1be6Step 3/9 : COPY httpserver.go . ---> 43a196658e09Step 4/9 : RUN go build -o myhttpserver ./httpserver.go ---> Running in 9e7b46f68e88 ---> 90dc73912803Removing intermediate container 9e7b46f68e88Step 5/9 : FROM alpine:latest ---> 053cde6e8953Step 6/9 : WORKDIR /root/ ---> Using cache ---> 30d95027ee6aStep 7/9 : COPY --from=builder /go/src/myhttpserver . ---> f1620b64c1baStep 8/9 : RUN chmod +x /root/myhttpserver ---> Running in e62809993a22 ---> 6be6c28f5fd6Removing intermediate container e62809993a22Step 9/9 : ENTRYPOINT /root/myhttpserver ---> Running in e4000d1dde3d ---> 639cec396c96Removing intermediate container e4000d1dde3dSuccessfully built 639cec396c96Successfully tagged myrepo/myhttserver-multi-stage:latest# docker imagesREPOSITORY                       TAG                 IMAGE ID            CREATED             SIZEmyrepo/myhttserver-multi-stage   latest              639cec396c96        About an hour ago   16.3MB

我們來Run一下這個image:

# docker run myrepo/myhttserver-multi-stage:latestWebserver start  -> listen on port:1111

四、小結

多階段鏡像構建可以讓開發人員通過一個Dockerfile,一次性地、更容易地構建出size較小的image,體驗良好並且更容易接入CI/CD等自動化系統。不過當前多階段構建僅是在Docker 17.05及之後的版本中才能得到支援。如果想學習和實踐這方面功能,但又沒有環境,可以使用play-with-docker提供的實驗環境。


Play with Docker labs

以上所有範例程式碼可以在這裡下載到。

微博:@tonybai_cn
公眾號:iamtonybai
github.com: https://github.com/bigwhite

2017, bigwhite. 著作權.

Related posts:

  1. Kuberize Ceph RBD API服務
  2. docker容器內服務程式的優雅退出
  3. 探討docker容器對共用記憶體的支援情況
  4. 探討Docker容器中修改系統變數的方法
  5. Kubernetes叢集Pod使用Host的本地時區設定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.