iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
DevOps

container & k8s 奏鳴曲系列 第 22

[13th][Day22] multistage

昨天建立 demo 這個 靜態執行檔是使用 gcc 這個 build container,然後在 scratch 內直接 ADD 執行檔

從 code 編譯成為 執行檔的過程中常需要常會用到許多其他額外的工具
接著 編譯完成的執行檔也可能會需要適當的環境或是其他背景才有辦法『成功執行』

雖然昨天達成了建構一個 『瘦瘦的』image ,但是在建構的過程當中如果需要很多額外應用的話仍複雜
docker 在 17版後引進了一個叫做 multistage build 這個厲害的東東

multistage build 使我可以在單一 dockerfile 中編排複雜的 build 工作
可以定義一個 or 多個 parent image
可以建立編譯過程中需要的所有環境
最後 只複製必要的素材到下一階段,就能獲得最低限度可以使用的輕量化 image

準備一個 app.c

#include <stdio.h>
void main(){
printf("Try multistage build");
}

準備一個 multistage Dockerfile

FROM gcc:7.2 AS builder
COPY src /src
RUN gcc -static -o /src/app /src/app.c && strip -R .comment -s /src/app

FROM scratch 
COPY --from=builder /src/app .
CMD ["./app"]

資料夾分佈如下
https://ithelp.ithome.com.tw/upload/images/20210929/20119546MHV4vHHGUw.png

build

docker build -t multistage .

https://ithelp.ithome.com.tw/upload/images/20210929/201195464UrjnFlsSW.png

run

docker run --rm multistage

https://ithelp.ithome.com.tw/upload/images/20210929/20119546pgan9OU4SS.png
成功印出 app.c 中 printf 的內容

在這個 dockerfile 中,作了兩次的 FROM
第一次建立一個靜態執行檔
第二次 FROM scratch 只 COPY 了 靜態執行檔
https://ithelp.ithome.com.tw/upload/images/20210929/20119546vIlOm4HSpF.png

可以看到這次 build 出來的 image 跟 trytry/nginx image 的容量差異
232000/738 ≒ 314 倍

去除了大部分的 docker image history
增加了 攜帶/傳送 的方便性


上一篇
[13th][Day21] scratch
下一篇
[13th][Day23] visualization
系列文
container & k8s 奏鳴曲30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言