docker镜像的分层(kvm 链接克隆,写时复制的特性)

镜像分层的好处:复用,节省磁盘空间,相同的内容只需加载一份到内存。
修改dockerfile之后,再次构建速度快
分层:就是在原有的基础镜像上新增了服务或者软件,也就是文件发生了大小变化。
例如,底层centos6.9,在这上新增nginx,在安装php;
11.docker镜像分层&dockerfile优化_nginx

通过镜像查看历史命令就能看出kod:v2镜像的大小变化有10层;注:下图基于基础镜像centos6.9就是一层
因为每一次构建镜像的时候都会起一个临时容器ID,执行下一个容器便会删除上一个容器ID,依次类推。
11.docker镜像分层&dockerfile优化_插入图片_02

镜像历史命令能看构建10层,也就是对应dockerfile脚本里面的发生文件大小变化的10条命令;
11.docker镜像分层&dockerfile优化_dockerfile优化_03

我将kod:v2镜像导出,然后删除kod:v2镜像,然后在导入,就可以清晰可见的层数
注释:由于centos6.9镜像已经存在,所以就直接复用了,就不会显示层数。
11.docker镜像分层&dockerfile优化_dockerfile优化_04

导入镜像,这里显示7层,正常来说应该是10层,因为这里有3层是在镜像中已经存在的,所以被直接复用。
注释:layer意思为:层
11.docker镜像分层&dockerfile优化_2d_05

从上面的结论可以得出,也就是构建脚本中的指令RUN越多层数就很多。下图所示
注释:docker镜像中分层限制最大128层。层数越多加载就越慢,所以越少越好
11.docker镜像分层&dockerfile优化_2d_06

dockerfile自动构建优化

dockerfile脚本优化:
1:尽可能选择体积小linux,如alpine(5M左右)
2:尽可能合并RUN指令,清理无用的文件(yum缓存,源码包)
3:修改dockerfile,把变化的内容尽可能放在dockerfile结尾
4: 使用.dockerignore,减少不必要的文件ADD . /html

根据上面几条优化规则,将kod服务构建的dockerfile脚本进行优化操作

[root@yunlong /data/dockerfile/kod]# cat dockerfile  
#!/bin/bash
FROM centos:6.9
RUN curl -o /etc/yum.repos.d/CentOS-Base.repo https://www.xmpan.com/Centos-6-Vault-Aliyun.repo && \
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-archive-6.repo && \
yum install  nginx php-fpm php-gd php-mbstring unzip -y && \
yum clean all 
ADD kodexplorer4.40.zip /opt/
RUN cd /opt/ && \
unzip kodexplorer4.40.zip && \
rm -rf kodexplorer4.40.zip && \ 
chown -R nginx:nginx .
ADD nginx.conf /etc/nginx/nginx.conf
ADD www.conf /etc/php-fpm.d/www.conf
ADD init.sh /init.sh
CMD ["/bin/bash","/init.sh"]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

重新构建镜像

docker build --network=host -t kod:v3 .
  • 1.

查看镜像比之前kodv2小了162M
11.docker镜像分层&dockerfile优化_2d_07

导出镜像查看,kod:v3小了156M
11.docker镜像分层&dockerfile优化_2d_08

在查看镜像历史命令显示kod:v2是10层,kod:v3则为7层。
11.docker镜像分层&dockerfile优化_dockerfile优化_09