大家好,我是地鼠哥,最近在带着大家做项目的时候碰到了一个印象很深的问题,和大家总结分享一下:明明代码逻辑没问题,部署时却频频报错,排查半天发现是服务器磁盘被占满了?
今天把解决思路整理出来,不仅能帮你快速释放磁盘空间,也想顺便安利下我们的项目课程(https://mp.weixin.qq.com/s/ACzEHtvGh2YsU_4fxo83fQ),里面还包含了更多部署运维的实战技巧哦~
Docker 运行时会产生大量“临时资源”,比如:
这些资源默认不会自动删除,积累久了就会导致磁盘告警。好在 Docker 提供了专门的清理命令,一招就能解决大部分问题。
docker system prune 命令docker system prune 是 Docker 提供的系统级资源清理命令,用于自动删除以下未被使用的资源 :
⚠️ 默认不会删除 :
nginx:latest)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 产生的中间层缓存 |
$ 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
docker system prune -f
docker system prune -a -f
docker system prune --volumes -f
操作 | 风险 |
|---|---|
prune -a | 可能误删后续部署所需的镜像 |
prune --volumes | 永久删除数据库等持久化数据 |
在生产环境自动执行 | 可能导致服务恢复困难(缺少镜像) |
-f 运行,确认删除列表-a 和 --volumesdocker 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
磁盘管理是运维的基础工作。定期执行 docker system prune -f 能有效避免磁盘满的问题,配合 docker system df 监控,可让部署更顺畅。