🛠️ 核心解决方案:docker system prune 命令

📌 一、命令简介

docker system prune 是 Docker 提供的系统级资源清理命令,用于自动删除以下未被使用的资源 :

  • 已停止的容器(Stopped containers)
  • 悬空镜像(Dangling images)
  • 未被任何容器使用的自定义网络(Unused networks)
  • 构建缓存(Build cache)

⚠️ 默认不会删除 :

  • 正在运行的容器
  • 有标签且未被引用的镜像(如 nginx:latest
  • 数据卷(Volumes)
  • 默认网络(bridgehostnone

🛠️ 二、基本语法


docker system prune [OPTIONS]

常用选项
选项说明
-a--all同时删除所有未被使用的镜像 (不仅是悬空镜像)
-f--force跳过确认提示,直接执行清理(静默模式)
--filter按条件过滤要删除的资源(如 until=24h
--volumes额外删除未使用的本地卷(⚠️ 高危操作!)

🔍 三、详细行为说明

默认行为(不加 -a

执行 docker system prune 会删除:

资源类型删除条件
容器状态为 exitedcreated 等非运行状态
镜像仅 dangling=true(即 <none>:<none> 且无容器引用)
网络用户创建的自定义网络,且未被任何容器使用
构建缓存所有 docker build 产生的中间层缓存

🧪 四、使用示例

示例 1:交互式清理(推荐首次使用)

$ docker system prune WARNING! This will remove: - all stopped containers - all networks not used by at least one container - all dangling images - all build cache Are you sure you want to continue? [y/N] y

示例 2:静默清理(推荐使用)

docker system prune -f

示例 3:彻底清理(包括未使用的有标签镜像)

docker system prune -a -f

示例 4:清理 + 删除未使用卷(高危!)

docker system prune --volumes -f

🔒 五、安全性与风险控制

✅ 安全保障
  • 不影响正在运行的容器和服务
  • 不删除默认网络和关键系统资源
  • 卷(Volumes)默认保留,防止数据丢失
⚠️ 风险提示
操作风险
prune -a可能误删后续部署所需的镜像
prune --volumes永久删除数据库等持久化数据
在生产环境自动执行可能导致服务恢复困难(缺少镜像)
✅ 安全建议
  1. 先预览再执行:不加 -f 运行,确认删除列表

  2. 生产环境避免 -a 和 --volumes

  3. 重要镜像提前备份


docker save myapp:v1 -o myapp_v1.tar

  1. 定期监控磁盘使用

docker system df

📊 六、查看清理效果

清理前后对比磁盘占用:


# 清理前 docker system df # 执行清理 docker system prune -f # 清理后 docker system df

输出示例:


TYPE TOTAL ACTIVE SIZE RECLAIMABLE Images 10 3 2.1GB 1.4GB (66%) Containers 5 3 120MB 80MB (66%) Local Volumes 4 2 500MB 300MB (60%) Build Cache - - 800MB 800MB

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐