本文已参与「新人创作礼」活动,一起开启掘金创作之路。
传统的保持小体积的方法都是使用一个基础镜像,直接写Dockerfile,尽量使用少的指令,这样就可以防止层数增加后,镜像的体积变大。
但是总有时候会在容器内做一些操作,比如下载某个包,又不记得都干过啥,就不好去删文件和写Dockerfile,终于看到了一个工具 docker-squash ,下面来简单记录下使用方法
docker-squash简介
github介绍
Docker在构建图像时创建了许多层。有时,把它们放在图像中是不必要的,也不可取的。例如,Dockerfile ADD指令会创建一个包含你想要在图像中使用的文件的单层。当这些文件只是临时文件(例如您想要解包的产品分发版)时,问题就出现了。Docker会一直携带这个不必要的图层,即使你在下一层删除这些文件。这浪费了时间(需要推送/加载/保存更多数据)和资源(更大的图像)。
压缩有助于在逻辑层中组织图像。我们可以控制图像的结构,而不是拥有多个(几乎所有情况下)不必要的层。
看到docker-squash也已经出来好几年了,地址在github.com/goldmann/do…
docker-squash快速使用
下载
pip install docker-squash
简单使用
1、查看镜像的历史改变记录(比如我的banner:latest镜像)
docker history banner:latest
结果:
2、压缩
docker-squash -f 25 -t banner:new banner:latest #压缩25层
docker-squash -f <镜像号> -t banner:new banner:latest #从前压缩到指定的这一层
注意,25层是我这个镜像所有的层数,你也可以根据自己想压缩的数量来,也可以指定从现在的层压缩到具体的某一层
然后等一会之后,就显示成功了
可以看到被压缩的大小和百分比
3、help信息
$ docker-squash -h
usage: cli.py [-h] [-v] [--version] [-d] [-f FROM_LAYER] [-t TAG]
[--tmp-dir TMP_DIR] [--output-path OUTPUT_PATH]
image
Docker layer squashing tool
positional arguments:
image Image to be squashed
optional arguments:
-h, --help show this help message and exit
-v, --verbose Verbose output
--version Show version and exit
-d, --development Does not clean up after failure for easier debugging
-f FROM_LAYER, --from-layer FROM_LAYER
ID of the layer or image ID or image name. If not
specified will squash all layers in the image
-t TAG, --tag TAG Specify the tag to be used for the new image. By
default it'll be set to 'image' argument
--tmp-dir TMP_DIR Temporary directory to be created and used
--output-path OUTPUT_PATH
Path where the image should be stored after squashing.
If not provided, image will be loaded into Docker
daemon
结语
先介绍这么多啦,可以快速上手,其他具体操作我也没用过,可以去github上去看~
不过这个方法也有不好的地方,他会导致各层镜像id丢失,如上面的图,会显示‘missing’,看github的issue里也没有好的解决方法
这个博客也有一些使用方法Squashing Docker Images ·