常用的清理 Kubernetes 集群資源命令
長時間運行的集群,常會面臨各種資源耗盡的問題,另外磁盤不足時 Kubelet 還會主動清理鏡像增加不確定因素,本文提供了一些命令片段用于清理工作。
1. Kubernetes 基礎對象清理
- 清理 Evicted 狀態的 Pod
- kubectl get pods --all-namespaces -o wide | grep Evicted | awk '{print $1,$2}' | xargs -L1 kubectl delete pod -n
- 清理 Error 狀態的 Pod
- kubectl get pods --all-namespaces -o wide | grep Error | awk '{print $1,$2}' | xargs -L1 kubectl delete pod -n
- 清理 Completed 狀態的 Pod
- kubectl get pods --all-namespaces -o wide | grep Completed | awk '{print $1,$2}' | xargs -L1 kubectl delete pod -n
- 清理沒有被使用的 PV
- kubectl describe -A pvc | grep -E "^Name:.*$|^Namespace:.*$|^Used By:.*$" | grep -B 2 "<none>" | grep -E "^Name:.*$|^Namespace:.*$" | cut -f2 -d: | paste -d " " - - | xargs -n2 bash -c 'kubectl -n ${1} delete pvc ${0}'
- 清理沒有被綁定的 PVC
- kubectl get pvc --all-namespaces | tail -n +2 | grep -v Bound | awk '{print $1,$2}' | xargs -L1 kubectl delete pvc -n
- 清理沒有被綁定的 PV
- kubectl get pv | tail -n +2 | grep -v Bound | awk '{print $1}' | xargs -L1 kubectl delete pv
2. Linux 清理
- 查看磁盤全部空間
- Filesystem Size Used Avail Use% Mounted on
- /dev/sda2 100G 47G 54G 47% /
- 查看指定目錄占用
- du -sh .
- 24G .
- 刪除指定前綴的文件夾
- cd /nfsdata
- ls | grep archived- |xargs -L1 rm -r
- 清理僵尸進程
- ps -A -ostat,ppid | grep -e '^[Zz]' | awk '{print }' | xargs kill -HUP > /dev/null 2>&1
3. Docker 清理
- 查看磁盤使用情況
- docker system df
- TYPE TOTAL ACTIVE SIZE RECLAIMABLE
- Images 361 23 178.5GB 173.8GB (97%)
- Containers 29 9 6.682GB 6.212GB (92%)
- Local Volumes 4 0 3.139MB 3.139MB (100%)
- Build Cache 0 0 0B 0B
- 清理 none 鏡像
- docker images | grep none | awk '{print $3}' | xargs docker rmi
- 清理不再使用的數據卷
- docker volume rm $(docker volume ls -q)
或者
- docker volume prune
- 清理緩存
- docker builder prune
- 全面清理
刪除關閉的容器、無用的存儲卷、無用的網絡、dangling 鏡像(無 tag 鏡像)
- docker system prune -f
- 清理正則匹配上的鏡像
這里清理的是 master-8bcf8d7-20211206-111155163 格式的鏡像。
- docker images |grep -E "([0-9a-z]*[-]){3,}[0-9]{9}" |awk '{print $3}' | xargs docker rmi
4. 設置定時
- 查看定時任務
- crontab -l
- 設置定時任務
- crontab -e
文本新增定時任務
- */35 */6 * * * docker images | grep none | awk '{print $3}' | xargs docker rmi
- 45 1 * * * docker system prune -f
這里第一個任務是每隔六個小時的第 35 分鐘執行,第二個任務每天的 1 時 45 分執行。
- 定時任務的格式
設置定時格式: * * * * * shell
第一個星號,minute,分鐘,值為 0-59 第二個星號,hour,小時,值從 0-23 第三個星號,day,天,值為從 1-31 第四個星號,month,月,值為從 1-12 月,或者簡寫的英文,比如 Nov、Feb 等 第五個星號,week 周,值為從 0-6 或者簡寫的英文,Wen、Tur 等,代表周幾,其中 0 代表周末