定时清理docker私服镜像

  • 2019 年 10 月 3 日
  • 笔记

定时清理docker私服镜像

使用CI构建docker镜像进行发布极大促进了大家的版本发布效率,于是镜像仓库也就急速膨胀。为了缓解磁盘压力,我们需要设置一些清理策略。

对于不同docker镜像的清理策略应该是不同的。比如,默认保留最近5个版本的镜像,对于工具类的image保留全部,对于业务类的image保留一个月之类的。

简单保留5个image的方式如下:

下载https://github.com/mlabouardy/nexus-cli, 使用cli来执行删除。

下载

wget https://s3.eu-west-2.amazonaws.com/nexus-cli/1.0.0-beta/linux/nexus-cli  chmod +x nexus-cli  

配置

./nexus-cli configure

最终会在本目录下创建.credentials 文件

# Nexus Credentials  nexus_host = "http://nexus.demo.com"  nexus_username = "admin"  nexus_password = "adminpass"  nexus_repository = "your-docker-private-repo"

注意,host填写的nexus的host和端口,不是docker对应的repo的端口。
nexus_repository就是docker对应的repo。

查看镜像

./nexus-cli image ls

保留最近5个

./nexus-cli image delete -name mlabouardy/nginx -keep 5

综合脚本

clean.sh

image_file=image.txt  CLI_HOME=/data/nexus3  KEEP_VERSION_NUM=5    $CLI_HOME/nexus-cli image ls > $image_file  sed -i '$d' $image_file      cat $image_file | while read line  do      echo "清理$line"      $CLI_HOME/nexus-cli image delete -name $line -keep $KEEP_VERSION_NUM  done

定时任务

crontab -e    0 2 * * * sh /data/nexus3/clean.sh  

创建nexus task

思考

前面提到,对应不同的image,应该选择不同的保留策略的。当然不能直接保留5个。比如某个工具镜像,虽然开发很勤快,但应用的也许还是老版本。对于业务镜像,一天发布了n次,添加了n个镜像。怎么维护这些版本呢?

一个粗略的想法是,规范image名称,比如tools-, biz-之类添加前缀。

分不同的repo。 对于工具类,单独一个repo,业务自己一个repo,对不同的repo执行不同的保留策略。