定時清理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執行不同的保留策略。