本文节选自我的博客文章:构建可靠、安全、最小化的 Docker 镜像: 原理与实践.

正如Code Review一样,代码审查可以大大提升企业项目的质量。容器镜像同样作为开发人员或是运维人员的产出物,对其进行审查也是必要的。

虽然我们可以通过docker命令结合文件系统浏览的方式进行容器镜像的审查,但其过程需要人工参与,很难做到自动化,更别提将镜像审查集成到CI过程中了。但一个好的工具可以帮我们做到这点。

向大家推荐一个非常棒的开源项目dive,具体安装请参考其项目页。它不但可以方便我们查询具体镜像层的详细信息,还可以作为CI持续集成过程中的镜像审查之用。使用它可以大大提升我们审查镜像的速度,并且可以将这个过程做成自动化。

该项目的具体动态操作图示如下:

如果作为镜像审查之后,可以进行如下命令操作:

$: CI=true dive <image-id>Fetching image... (this can take a while with large images)Parsing image...Analyzing image...  efficiency: 95.0863 %  wastedBytes: 671109 bytes (671 kB)  userWastedPercent: 8.2274 %Run CI Validations...  Using default CI config  PASS: highestUserWastedPercent  SKIP: highestWastedBytes: rule disabled  PASS: lowestEfficiency

从输出信息可以得到很多有用的信息,集成到CI过程也就非常容易了。 dive本身就提供了.dive-ci作为项目的CI配置:

rules:  # If the efficiency is measured below X%, mark as failed.  # Expressed as a percentage between 0-1.  lowestEfficiency: 0.95  # If the amount of wasted space is at least X or larger than X, mark as failed.  # Expressed in B, KB, MB, and GB.  highestWastedBytes: 20MB  # If the amount of wasted space makes up for X% or more of the image, mark as failed.  # Note: the base image layer is NOT included in the total image size.  # Expressed as a percentage between 0-1; fails if the threshold is met or crossed.  highestUserWastedPercent: 0.20

集成到CI中,增加以下命令即可:

$: CI=true dive <image-id> 

镜像审查和代码审查类似,是一件开始抵制,开始后就欲罢不能的事。这件事宜早不宜迟,对于企业与个人而言均百利而无一害。