Docker磁盘满了?这样清理高效又安全
🛠️ 核心解决方案:docker system prune 命令
📌 一、命令简介
docker system prune 是 Docker 提供的系统级资源清理命令,用于自动删除以下未被使用的资源 :
- 已停止的容器(Stopped containers)
- 悬空镜像(Dangling images)
- 未被任何容器使用的自定义网络(Unused networks)
- 构建缓存(Build cache)
⚠️ 默认不会删除 :
- 正在运行的容器
- 有标签且未被引用的镜像(如
nginx:latest)- 数据卷(Volumes)
- 默认网络(
bridge、host、none)
🛠️ 二、基本语法
docker system prune [OPTIONS]
常用选项
| 选项 | 说明 |
|---|---|
-a, --all | 同时删除所有未被使用的镜像 (不仅是悬空镜像) |
-f, --force | 跳过确认提示,直接执行清理(静默模式) |
--filter | 按条件过滤要删除的资源(如 until=24h) |
--volumes | 额外删除未使用的本地卷(⚠️ 高危操作!) |
🔍 三、详细行为说明
默认行为(不加 -a)
执行 docker system prune 会删除:
| 资源类型 | 删除条件 |
|---|---|
| 容器 | 状态为 exited、created 等非运行状态 |
| 镜像 | 仅 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 | 永久删除数据库等持久化数据 |
| 在生产环境自动执行 | 可能导致服务恢复困难(缺少镜像) |
✅ 安全建议
-
先预览再执行:不加
-f运行,确认删除列表 -
生产环境避免
-a和--volumes -
重要镜像提前备份:
docker save myapp:v1 -o myapp_v1.tar
- 定期监控磁盘使用:
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
更多推荐



所有评论(0)