From 2a7f18fa64fda104252cfea44327cb9c9d6b2d28 Mon Sep 17 00:00:00 2001 From: mini2024 Date: Sat, 22 Mar 2025 16:25:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20Docker=20=E6=B8=85?= =?UTF-8?q?=E7=90=86=E8=84=9A=E6=9C=AC=EF=BC=8C=E6=94=AF=E6=8C=81=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E8=B5=84=E6=BA=90=E3=80=81=E6=9E=84=E5=BB=BA=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E3=80=81=E9=95=9C=E5=83=8F=E5=92=8C=E5=8D=B7=E7=9A=84?= =?UTF-8?q?=E6=B8=85=E7=90=86=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker-cleanup.sh | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 docker-cleanup.sh diff --git a/docker-cleanup.sh b/docker-cleanup.sh new file mode 100644 index 0000000..8593a4f --- /dev/null +++ b/docker-cleanup.sh @@ -0,0 +1,63 @@ +#!/bin/bash + +# 定义颜色 +RED='\033[0;31m' +GREEN='\033[0;32m' +NC='\033[0m' # No Color + +# 检查是否以 root 或具有 docker 权限运行 +if ! docker info >/dev/null 2>&1; then + echo -e "${RED}错误:需要 Docker 权限。请以 root 或 docker 组用户运行此脚本${NC}" + exit 1 +fi + +# 记录开始时间 +START_TIME=$(date +%s) + +echo -e "${GREEN}开始清理 Docker 环境...${NC}" + +# 函数:执行清理并显示结果 +execute_cleanup() { + local command="$1" + local description="$2" + echo -n "正在 $description..." + local output=$($command 2>&1) + if [ $? -eq 0 ]; then + echo -e "${GREEN}完成${NC}" + if [ ! -z "$output" ]; then + echo "$output" | grep -i "total reclaimed" || echo "$output" + fi + else + echo -e "${RED}失败${NC}" + echo "错误信息: $output" + fi +} + +# 执行清理操作 +execute_cleanup "docker system prune --all --force" "清理系统资源" +execute_cleanup "docker builder prune --all --force" "清理构建缓存" +execute_cleanup "docker buildx prune --all --force" "清理 buildx 缓存" +execute_cleanup "docker image prune --all --force" "清理镜像" +execute_cleanup "docker network prune --force" "清理网络" + +# 处理卷清理 +echo -n "正在清理未使用的卷..." +dangling_volumes=$(docker volume ls --quiet --filter="dangling=true") +if [ ! -z "$dangling_volumes" ]; then + docker volume rm $dangling_volumes >/dev/null 2>&1 + if [ $? -eq 0 ]; then + echo -e "${GREEN}完成${NC}" + else + echo -e "${RED}部分或全部卷清理失败${NC}" + fi +else + echo -e "${GREEN}无未使用卷需要清理${NC}" +fi + +execute_cleanup "docker volume prune --all --force" "执行最终卷清理" + +# 计算执行时间 +END_TIME=$(date +%s) +EXECUTION_TIME=$((END_TIME - START_TIME)) + +echo -e "\n${GREEN}清理完成!总耗时:${EXECUTION_TIME}秒${NC}" \ No newline at end of file