写在前面
这篇小作文我们会学习镜像构建的另一个关键性问题,为何别人打造的镜像只有10MB而我的有几百MB?如何精简镜像减小镜像体积?
精简镜像我们可以从两个方面切入:
- 减少镜像层数
- 缩减容量
一、减少镜像层数
1.指令合并
Dockerfile 中的每条指令都将创建一个层,不过查看官方文档中最佳实践有这样一句话:
In older versions of Docker, it was important that you minimized the number of layers in your images to ensure they were performant. The following features were added to reduce this limitation:
-
Only the instructions
RUN
,COPY
,ADD
create layers. Other instructions create temporary intermediate images, and do not increase the size of the build....
参考地址:Minimize the number of layers
意味着只有 RUN
, COPY
, ADD
三个指令会创建层,其他指令会创建一个中间镜像,并且不会影响镜像大小。这样我们说的指令合并也就是以这三个指令为主。
我们以如下Dockerfile为例
FROM debian:stable
WORKDIR /var/www
LABEL version=“v1”
RUN apt-get update
RUN apt-get -y --no-install-recommends install curl
RUN apt-get purge -y curl
RUN apt-get autoremove -y
RUN apt-g