镜像的缓存特性 - 天天5分钟玩转 Docker 容器技术(14)

上一节咱们学习了镜像的分层结构,今天讨论镜像的缓存特性。

docker

Docker 会缓存已有镜像的镜像层,构建新镜像时,若是某镜像层已经存在,就直接使用,无需从新建立。ubuntu

举例说明。
在前面的 Dockerfile 中添加一点新内容,往镜像中复制一个文件: vim

73.png

root@ubuntu:~# ls           ① 缓存

Dockerfile  testfile 学习

root@ubuntu:~# ui

root@ubuntu:~# docker build -t ubuntu-with-vi-dockerfile-2 . spa

Sending build context to Docker daemon 32.77 kB 调试

Step 1 : FROM ubuntu code

 ---> f753707788c5 orm

Step 2 : RUN apt-get update && apt-get install -y vim

 ---> Using cache         ②

 ---> 35ca89798937

Step 3 : COPY testfile /          ③

 ---> 8d02784a78f4

Removing intermediate container bf2b4040f4e9

Successfully built 8d02784a78f4


① 确保 testfile 已存在。

② 重点在这里:以前已经运行过相同的 RUN 指令,此次直接使用缓存中的镜像层 35ca89798937。

③ 执行 COPY 指令。
其过程是启动临时容器,复制 testfile,提交新的镜像层 8d02784a78f4,删除临时容器。

在 ubuntu-with-vi-dockerfile 镜像上直接添加一层就获得了新的镜像 ubuntu-with-vi-dockerfile-2。

若是咱们但愿在构建镜像时不使用缓存,能够在 docker build 命令中加上 --no-cache 参数。

Dockerfile 中每个指令都会建立一个镜像层,上层是依赖于下层的。不管何时,只要某一层发生变化,其上面全部层的缓存都会失效。

也就是说,若是咱们改变 Dockerfile 指令的执行顺序,或者修改或添加指令,都会使缓存失效。

举例说明,好比交换前面 RUN 和 COPY 的顺序:

虽然在逻辑上这种改动对镜像的内容没有影响,但因为分层的结构特性,Docker 必须重建受影响的镜像层。

root@ubuntu:~# docker build -t ubuntu-with-vi-dockerfile-3 .

Sending build context to Docker daemon 37.89 kB

Step 1 : FROM ubuntu

 ---> f753707788c5

Step 2 : COPY testfile /

 ---> bc87c9710f40

Removing intermediate container 04ff324d6af5

Step 3 : RUN apt-get update && apt-get install -y vim

 ---> Running in 7f0fcb5ee373

Get:1 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB]

......


从上面的输出能够看到生成了新的镜像层 bc87c9710f40,缓存已经失效。

除了构建时使用缓存,Docker 在下载镜像时也会使用。例如咱们下载 httpd 镜像。

docker pull 命令输出显示第一层(base 镜像)已经存在,不须要下载。

由 Dockerfile 可知 httpd 的 base 镜像为 debian,正好以前已经下载过 debian 镜像,因此有缓存可用。经过 docker history 能够进一步验证。

下一节咱们学习如何调试 Dockerfile。

二维码+指纹.png

相关文章
相关标签/搜索