如何理解Docker鏡像分層?且聽百度高級研發(fā)工程師細細道來

目錄

  • 關(guān)于base鏡像
  • 關(guān)于存儲結(jié)構(gòu)(About storage drivers)
    • 先來創(chuàng)建一個自己的鏡像
    • docker鏡像的分層結(jié)構(gòu)
    • 容器的大小
    • 修改時復(fù)制策略 copy-on-write (CoW)
    • Copying makes containers efficient

關(guān)于base鏡像

base 鏡像有兩層含義:

  • 不依賴其他鏡像,從 scratch 構(gòu)建。
  • 其他鏡像可以之為基礎(chǔ)進行擴展。

所以,能稱作 base 鏡像的通常都是各種 Linux 發(fā)行版的 Docker 鏡像,比如 Ubuntu, Debian, CentOS 等。

base 鏡像提供的是最小安裝的 Linux 發(fā)行版。

我們大部分鏡像都將是基于base鏡像構(gòu)建的。所以,通常使用的是官方發(fā)布的base鏡像??梢栽赿ocker hub里找到。比如centos: https://hub.docker.com/_/centos

點擊版本可以看到github里的Dockerfile

FROM scratch
ADD centos-7-docker.tar.xz /

LABEL org.label-schema.schema-version="1.0" \
    org.label-schema.name="CentOS Base Image" \
    org.label-schema.vendor="CentOS" \
    org.label-schema.license="GPLv2" \
    org.label-schema.build-date="20181205"

CMD ["/bin/bash"]

ADD命令將本地的centos7的tar包添加到鏡像,并解壓到根目錄/下。生成/dev,/proc/,/bin等。

我們可以自己構(gòu)建docker base鏡像,也可以直接使用已有的base鏡像。比如centos。我們可以直接從docker hub上拉取。

拉取

docker pull centos

查看

# docker images centos 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              1e1148e4cc2c        2 months ago        202MB

可以看到最新的centos鏡像只有200mb,是不是覺得太小了?這是因為docker鏡像在運行的時候直接使用docker宿主機器的kernel。

Linux操作系統(tǒng)由內(nèi)核空間和用戶空間組成。

內(nèi)核空間是kernel,用戶空間是rootfs, 不同Linux發(fā)行版的區(qū)別主要是rootfs.比如 Ubuntu 14.04 使用 upstart 管理服務(wù),apt 管理軟件包;而 CentOS 7 使用 systemd 和 yum。這些都是用戶空間上的區(qū)別,Linux kernel 差別不大。

所以 Docker 可以同時支持多種 Linux 鏡像,模擬出多種操作系統(tǒng)環(huán)境。

需要注意的是

  • base鏡像只是用戶空間和發(fā)行版一致。kernel使用的是docker宿主機器的kernel。例如 CentOS 7 使用 3.x.x 的 kernel,如果 Docker Host 是 Ubuntu 16.04(比如我們的實驗環(huán)境),那么在 CentOS 容器中使用的實際是是 Host 4.x.x 的 kernel。
  • ① Host kernel 為 4.4.0-31
  • ② 啟動并進入 CentOS 容器
  • ③ 驗證容器是 CentOS 7
  • ④ 容器的 kernel 版本與 Host 一致

關(guān)于存儲結(jié)構(gòu)(About storage drivers)

上文里展示了如何下載一個base鏡像。我們通常是基于這份base鏡像來構(gòu)建我們自己的鏡像。比如,在centos里添加一個nginx負載均衡。首先,得需要了解鏡像的結(jié)構(gòu)是什么。

官方文檔: https://docs.docker.com/storage/storagedriver/

先來創(chuàng)建一個自己的鏡像

首先,base鏡像是基于docker宿主機器kernel之上的Linux發(fā)行版。

現(xiàn)在,我們給這臺機器安裝一個vim,一個httpd. 基于Dockerfile來創(chuàng)建一個新的鏡像。

我們的Dockerfile

FROM centos:7
RUN yum install -y vim
RUN yum install -y httpd
CMD ["/bin/bash"]

含義:

  • 基于centos7的base鏡像構(gòu)建
  • 安裝vim
  • 安裝httpd
  • 執(zhí)行bash

在當(dāng)前目錄下新建一個文件Dockerfile, 填充上述內(nèi)容。然后執(zhí)行

# docker build -t ryan/httpd:v1.0 .
Sending build context to Docker daemon  6.144kB
Step 1/4 : FROM centos:7
 ---> 1e1148e4cc2c
Step 2/4 : RUN yum install -y vim
 ---> Using cache
 ---> 74bdbea98f73
Step 3/4 : RUN yum install -y httpd
 ---> Using cache
 ---> 17d8c4095dc4
Step 4/4 : CMD /bin/bash
 ---> Using cache
 ---> f2b58b1192de
Successfully built f2b58b1192de
Successfully tagged ryan/httpd:latest
  • -t 指定我們創(chuàng)建的鏡像名稱,鏡像名稱可以用組織/id:version的方式標(biāo)記
  • 最后一個參數(shù)是Dockerfile所在的路徑., 表示當(dāng)前目錄

然后我們添加一個tag latest

docker tag ryan/httpd:v1.0 ryan/httpd:latest
  • 即給鏡像ryan/httpd:v1.0標(biāo)記為ryan/httpd:latest

構(gòu)建完成之后,查看

# docker images  | grep -E '(ryan|centos)'
ryan/httpd                                                               latest                     f2b58b1192de        About an hour ago   444MB
ryan/httpd                                                               v1.0                       f2b58b1192de        About an hour ago   444MB
centos                                                                   7                          1e1148e4cc2c        2 months ago        202MB
centos                                                                   latest                     1e1148e4cc2c        2 months ago        202MB

可以運行我們創(chuàng)建的鏡像:

# docker run -d  --privileged=true -it ryan/httpd:v1.0 /usr/sbin/init
48a4a128cd7b6924149cd97670919d4e2af6cb96c73c901af60d05fe4478225a
# docker ps | grep ryan
48a4a128cd7b        ryan/httpd:v1.0                                                          "/usr/sbin/init"         8 seconds ago       Up 8 seconds       

現(xiàn)在我們的基于原生base centos7的httpd服務(wù)器已經(jīng)啟動了??梢酝ㄟ^docker exec -it zealous_kirch /bin/bash來進入容器內(nèi)部,查看啟動httpd。

docker鏡像的分層結(jié)構(gòu)

我們可以查看鏡像的歷史,用上一步的鏡像id f2b58b1192de

# docker history f2b58b1192de
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
f2b58b1192de        About an hour ago   /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
17d8c4095dc4        About an hour ago   /bin/sh -c yum install -y httpd                 110MB               
74bdbea98f73        About an hour ago   /bin/sh -c yum install -y vim                   133MB               
1e1148e4cc2c        2 months ago        /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
<missing>           2 months ago        /bin/sh -c #(nop)  LABEL org.label-schema....   0B                  
<missing>           2 months ago        /bin/sh -c #(nop) ADD file:6f877549795f479...   202MB   

啟動鏡像的時候,一個新的可寫層會加載到鏡像的頂部。這一層通常稱為“容器層”, 之下是“鏡像層”。

容器層可以讀寫,容器所有發(fā)生文件變更寫都發(fā)生在這一層。鏡像層read-only,只允許讀取。

(上圖來自官方文檔,和本次實驗內(nèi)容略有不同,但原理一樣)

第一列是imageid, 最上面的id就是我們新創(chuàng)建ryan/httpd:latest. 下面幾行都是我們dockerfile里定義的步驟堆棧。由此可以看出,每個步驟都將創(chuàng)建一個imgid, 一直追溯到1e1148e4cc2c正好是我們的base鏡像的id。關(guān)于<missing>的部分,則不在本機上。

最后一列是每一層的大小。最后一層只是啟動bash,所以沒有文件變更,大小是0. 我們創(chuàng)建的鏡像是在base鏡像之上的,并不是完全復(fù)制一份base,然后修改,而是共享base的內(nèi)容。這時候,如果我們新建一個新的鏡像,同樣也是共享base鏡像。

那修改了base鏡像,會不會導(dǎo)致我們創(chuàng)建的鏡像也被修改呢? 不會!因為不允許修改歷史鏡像,只允許修改容器,而容器只可以在最上面的容器層進行寫和變更。

容器的大小

創(chuàng)建鏡像的時候,分層可以讓docker只保存我們添加和修改的部分內(nèi)容。其他內(nèi)容基于base鏡像,不需要存儲,讀取base鏡像即可。如此,當(dāng)我們創(chuàng)建多個鏡像的時候,所有的鏡像共享base部分。節(jié)省了磁盤空間。

對于啟動的容器,查看所需要的磁盤空間可以通過docker ps -s

# docker run -d -it centos
4b0df4bc3e705c540144d545441930689124ade087961d01f56c2ac55bfd986d
# docker ps -s | grep -E '(ryan|centos)'
4b0df4bc3e70        centos                                                                   "/bin/bash"              23 seconds ago      Up 23 seconds                           vigorous_elion                                                                                                                           0B (virtual 202MB)
b36421d05005        ryan/httpd:v1.0                                                          "/usr/sbin/init"         32 minutes ago      Up 32 minutes                           gracious_swirles                                                                                                                         61.6kB (virtual 444MB)
  • 首先啟動一個base鏡像用來對比
  • 可以看到第一行就是base鏡像centos,第2列的size是0和202MB, 0表示容器層可寫層的大小,virtual則是容器層+鏡像層的大小。這里對比可以看到一共202M,正好是最初centos鏡像的大小。
  • 第二行是我們自己創(chuàng)建的鏡像。virtual達到了444MB。對比前面的history部分,可以發(fā)現(xiàn)這個數(shù)字是每一層大小之和。同時,由于共享base,其中的202M是和第一行的鏡像共享的。

修改時復(fù)制策略 copy-on-write (CoW)

docker通過一個叫做copy-on-write (CoW) 的策略來保證base鏡像的安全性,以及更高的性能和空間利用率。

Copy-on-write is a strategy of sharing and copying files for maximum efficiency. If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file (when building the image or running the container), the file is copied into that layer and modified. This minimizes I/O and the size of each of the subsequent layers. These advantages are explained in more depth below.

Copying makes containers efficient

When you start a container, a thin writable container layer is added on top of the other layers. Any changes the container makes to the filesystem are stored here. Any files the container does not change do not get copied to this writable layer. This means that the writable layer is as small as possible.

When an existing file in a container is modified, the storage driver performs a copy-on-write operation. The specifics steps involved depend on the specific storage driver. For the aufs, overlay, and overlay2 drivers, the copy-on-write operation follows this rough sequence:

Search through the image layers for the file to update. The process starts at the newest layer and works down to the base layer one layer at a time. When results are found, they are added to a cache to speed future operations.

Perform a copy_up operation on the first copy of the file that is found, to copy the file to the container’s writable layer.

Any modifications are made to this copy of the file, and the container cannot see the read-only copy of the file that exists in the lower layer.

Btrfs, ZFS, and other drivers handle the copy-on-write differently. You can read more about the methods of these drivers later in their detailed descriptions.

Containers that write a lot of data consume more space than containers that do not. This is because most write operations consume new space in the container’s thin writable top layer.

簡單的說,啟動容器的時候,最上層容器層是可寫層,之下的都是鏡像層,只讀層。

當(dāng)容器需要讀取文件的時候

從最上層鏡像開始查找,往下找,找到文件后讀取并放入內(nèi)存,若已經(jīng)在內(nèi)存中了,直接使用。(即,同一臺機器上運行的docker容器共享運行時相同的文件)。

當(dāng)容器需要添加文件的時候

直接在最上面的容器層可寫層添加文件,不會影響鏡像層。

當(dāng)容器需要修改文件的時候

從上往下層尋找文件,找到后,復(fù)制到容器可寫層,然后,對容器來說,可以看到的是容器層的這個文件,看不到鏡像層里的文件。容器在容器層修改這個文件。

當(dāng)容器需要刪除文件的時候

從上往下層尋找文件,找到后在容器中記錄刪除。即,并不會真正的刪除文件,而是軟刪除。這將導(dǎo)致鏡像體積只會增加,不會減少。

綜上,Docker鏡像通過分層實現(xiàn)了資源共享,通過copy-on-write實現(xiàn)了文件隔離。

對于文件只增加不減少問題,我們應(yīng)當(dāng)在同一層做增刪操作,從而減少鏡像體積。比如,如下測試。

Dockerfile.A: 分層刪除文件

FROM centos:7
RUN yum install -y vim
RUN yum install -y httpd
WORKDIR /home
RUN dd if=/dev/zero of=50M.file bs=1M count=50
#創(chuàng)建大小為50M的測試文件
RUN rm -rf 50M.file
CMD ["/bin/bash"]

構(gòu)建

docker build -t test:a -f Dockerfile.A .

Dockerfile.B: 同層刪除

FROM centos:7
RUN yum install -y vim
RUN yum install -y httpd
WORKDIR /home
RUN dd if=/dev/zero of=50M.file bs=1M count=50 && rm -rf 50M.file

構(gòu)建

docker build -t test:b -f Dockerfile.B .

比較二者大小

[root@sh-k8s-001 tmp]# docker images | grep test
test                                                                     a                          ae673aa7db48        9 minutes ago       497MB
test                                                                     b                          21b2bc49f0bd        12 minutes ago      444MB

顯然,分層刪除操作并沒有真正刪除掉文件。

寫在最后

點關(guān)注,不迷路;持續(xù)更新Java相關(guān)技術(shù)及資訊文章

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • docker基本概念 1. Image Definition 鏡像 Image 就是一堆只讀層 read-only...
    慢清塵閱讀 9,005評論 1 21
  • 一、Docker 簡介 Docker 兩個主要部件:Docker: 開源的容器虛擬化平臺Docker Hub: 用...
    R_X閱讀 4,521評論 0 27
  • 百嶺溝里秋色濃
    放下_c1af閱讀 176評論 0 0
  • 概述 Worker的啟動都是通過啟動shell腳本 Master啟動 master啟動從main函數(shù)開始,主要啟動...
    scandly閱讀 537評論 0 1
  • 今天上午上完主題課之后,悅悅老師在接小朋友,在接小朋友的時候,恩恩和王子一起來的,今天是我第一次見到王子呢!...
    月落孤倚閱讀 213評論 0 0

友情鏈接更多精彩內(nèi)容