Docker 以及一般的容器引擎都使用联合挂载文件系统概念。
联合安装 https://en.wikipedia.org/wiki/Union_mount是一种将多个目录组合成一个看起来包含其组合内容的目录的方法。
因此,图像实际上是由原子不可变文件夹(又名“层”)组成。
该机制的主要目标是重复数据删除。
一层可以由多个图像共享,从而节省大量存储空间。
例如您下载 CentOS 基础映像 (700mb) 并在其上构建多个自定义映像。
CentOS 的大部分仍然存储一次 - 您的图像只是引用它。
Anoher 好答案 https://stackoverflow.com/a/32776204/4486909- 旧的,但仍然相关。
当你使用 Dockerfile 构建镜像时,Dockerfile 中的每个单独的命令都会生成一个新层,将其放在前一个之上(或“合并”它们 - 就联合文件系统而言)。
生成的图像将包含所有中间层在您的构建过程中创建。
FROM busybox
# layer 1: added test1 50 mb
RUN dd if=/dev/zero of=/tmp/test1 bs=1M count=50
# layer 2: added test2 50 mb
RUN dd if=/dev/zero of=/tmp/test2 bs=1M count=50
# layer 3: "removed" test1, but actually test1 still lives in layer 1
# "removal" just made it invisible for upper layers
# that is how removal works in union mount file systems
# technically, in terms of UFS, it's not a "removal", but a "merge" of layer 3 with layer 1
RUN rm -rf /tmp/test1
# layer 4: same as layer 3
RUN rm -rf /tmp/test2
节省空间的常见方法是将 shell 命令链接到单个 RUN 指令下。
# in this case only one layer will be created
# it will contain eventual state of the filesystem after full command chain completion
RUN dd if=/dev/zero of=/tmp/test1 bs=1M count=50 && \
dd if=/dev/zero of=/tmp/test2 bs=1M count=50 && \
rm -rf /tmp/test1 && \
rm -rf /tmp/test2