# Docker 磁盘空间清理

## Docker 磁盘空间清理（主机）

Docker 数据会随着主机使用时间增长。\
旧租用留下已停止的容器、未使用的镜像、卷和构建缓存。\
如果不清理，根磁盘会被填满，部署会开始失败。

{% hint style="info" %}
仅在服务器 **未被租用** 且您不需要任何旧容器数据时运行清理。\
如果不确定，请先停止此操作并先检查磁盘使用情况。
{% endhint %}

***

## 1) 检查磁盘使用情况

### 操作系统级别磁盘空间（`df -h`)

这会显示每个挂载的文件系统的可用空间。

```bash
df -h
```

您主要关心 `/` （根）以及包含 `/var/lib/docker`.

### Docker 级别磁盘使用情况（`docker system df`)

这会显示 Docker 存储的内容以及可回收的空间量。

```bash
docker system df
```

如果您想查看每个镜像/容器的更多细节：

```bash
docker system df -v
```

***

## 2) 完全清理（推荐）

这是“重置来自之前租用的 Docker 残留”命令。\
它会移除未使用的容器、镜像、网络和 **未使用的卷**.

```bash
docker system prune -a --volumes
```

{% hint style="warning" %}
`-a` 移除 **所有未使用的镜像**，不仅仅是“悬空”镜像。\
这包括为了加速将来部署而可能希望保留的缓存镜像。
{% endhint %}

***

## 3) 单独清理命令（更可控）

当您只想清理特定类别时使用这些命令。\
它们更适合增量维护且更安全。

### 容器（仅已停止的）

```bash
docker container prune
```

### 镜像（未使用的）

仅移除悬空层：

```bash
docker image prune
```

移除所有未使用的镜像（与 `system prune -a`):

```bash
相同风险）：docker image prune -a
```

### 卷（未使用的）

```bash
docker volume prune
```

### 网络（未使用的）

```bash
docker network prune
```

***

## 4) 主机维护的最佳实践

1. 在以下时机清理 **租用之间** 或在计划停机期间。
2. 保留安全缓冲。\
   目标是始终在根磁盘上保留 **10–20 GB** 空闲空间。
3. 定期检查 Docker 使用情况：
   * `df -h`
   * `docker system df`
4. 优先先进行增量清理：
   * `docker container prune`
   * `docker image prune`
   * `docker volume prune`
5. 仅在必要时使用完全清理：
   * `docker system prune -a --volumes`
6. 如果磁盘使用量持续快速增长，请调查：
   * 租用者创建的大型卷。
   * 位于以下位置的日志 `/var/lib/docker/containers/*/*.log`.
   * 由频繁镜像重建产生的构建缓存。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/clore.ai/clore.ai-eng-zh/zhen-dui-zhu-ji/server-offline-on-clore.ai/docker-disk-space-cleanup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
