一.Dockerfile合理分层
Dockerfile的写法不合理,有时候会导致镜像膨胀,由于Docker是分层设计,而在Dockerfile中,每一条指令都拥有自己的context,而执行到下一条指令时,则会将下一层的构建层叠加到上一层上。因此,假如你在上一层指令做了一些包下载操作安装操作,然后在下一层再做清理,其实没什么用,只能说明你下一层引入的diff是0而已。
可以实验一下:
对照组A:下载清理操作全在同一层
FROM centos MAINTAINER ** RUN yum -y update RUN yum -y install wget RUN wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-linux-x64.tar.gz" -O /tmp/jdk8_x64.tar.gz && gunzip /tmp/jdk8_x64.tar.gz && tar -C /opt -xf /tmp/jdk8_x64.tar && ln -s /opt/jdk1.8.0_121 /opt/jdk && yum clean all && rm -fr /tmp/*
对照组B:下载清理操作放在不同层
FROM centos MAINTAINER ** RUN yum -y update RUN yum -y install wget RUN wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-linux-x64.tar.gz" -O /tmp/jdk8_x64.tar.gz && gunzip /tmp/jdk8_x64.tar.gz && tar -C /opt -xf /tmp/jdk8_x64.tar && ln -s /opt/jdk1.8.0_121 /opt/jdk RUN yum clean all RUN rm -fr /tmp/*
分别执行构建操作,得到的镜像差异很大,其中test1为对照组A的构建结果,test2为对照组B的构建结果,两者相差400M.
[email protected]:~/workspace/docker_project$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE test2 latest a65c6cced43b 13 minutes ago 1.1 GB test1 latest 67897397b053 14 minutes ago 729 MB
时间: 2024-10-09 06:18:17