Fix and update

This commit is contained in:
baohua
2026-02-09 11:34:35 -08:00
parent e669ee0fe8
commit 63377d0431
136 changed files with 2146 additions and 262 deletions

View File

@@ -1,5 +1,7 @@
## 删除容器
随着容器的创建和停止系统中会积累大量的容器本节将介绍如何删除不再需要的容器以及如何清理所有停止的容器
### 基本用法
使用 `docker rm` 删除已停止的容器
@@ -22,6 +24,8 @@ $ docker rm 容器名或ID
#### 删除已停止的容器
运行以下命令
```bash
$ docker rm mycontainer
mycontainer
@@ -29,12 +33,16 @@ mycontainer
#### 强制删除运行中的容器
运行以下命令
```bash
## 不加 -f 会报错
$ docker rm running_container
Error: cannot remove running container
## 加 -f 强制删除
$ docker rm -f running_container
running_container
```
@@ -43,8 +51,11 @@ running_container
#### 删除容器及其数据卷
运行以下命令
```bash
## 删除容器时同时删除其匿名卷
$ docker rm -v mycontainer
```
@@ -56,8 +67,11 @@ $ docker rm -v mycontainer
#### 删除所有已停止的容器
运行以下命令
```bash
## 方式一:使用 prune 命令(推荐)
$ docker container prune
WARNING! This will remove all stopped containers.
@@ -68,30 +82,40 @@ def456...
Total reclaimed space: 150MB
## 方式二:不提示确认
$ docker container prune -f
```
#### 删除所有容器包括运行中的
运行以下命令
```bash
## 先停止所有容器,再删除
$ docker stop $(docker ps -q)
$ docker rm $(docker ps -aq)
## 或者直接强制删除
$ docker rm -f $(docker ps -aq)
```
#### 按条件删除
运行以下命令
```bash
## 删除所有已退出的容器
$ docker rm $(docker ps -aq -f status=exited)
## 删除名称包含 "test" 的容器
$ docker rm $(docker ps -aq -f name=test)
## 删除 24 小时前创建的容器
$ docker container prune --filter "until=24h"
```
@@ -112,11 +136,15 @@ $ docker container prune --filter "until=24h"
#### 示例
运行以下命令
```bash
## 删除所有基于 nginx 镜像的容器
$ docker rm $(docker ps -aq -f ancestor=nginx)
## 删除所有创建后未启动的容器
$ docker rm $(docker ps -aq -f status=created)
```
@@ -128,10 +156,12 @@ $ docker rm $(docker ps -aq -f status=created)
```bash
## 尝试删除有容器依赖的镜像
$ docker image rm nginx
Error: image is being used by stopped container abc123
## 需要先删除依赖该镜像的容器
$ docker rm abc123
$ docker image rm nginx
```
@@ -142,27 +172,37 @@ $ docker image rm nginx
#### 开发环境
运行以下命令
```bash
## 定期清理已停止的容器
$ docker container prune -f
## 一键清理所有未使用资源
$ docker system prune -f
```
#### 生产环境
运行以下命令
```bash
## 使用 --rm 参数运行临时容器
$ docker run --rm ubuntu echo "Hello"
## 容器退出后自动删除
## 定期清理(设置保留时间)
$ docker container prune --filter "until=168h" # 保留 7 天内的
```
#### 完整清理脚本
运行以下命令
```bash
#!/bin/bash
## cleanup.sh - Docker 资源清理脚本
@@ -189,6 +229,8 @@ docker system df
#### Q: 容器无法删除
运行以下命令
```bash
Error: container is running
```
@@ -199,6 +241,7 @@ Error: container is running
$ docker stop mycontainer
$ docker rm mycontainer
## 或
$ docker rm -f mycontainer
```
@@ -213,9 +256,11 @@ $ docker rm -f mycontainer
```bash
## 查看空间占用
$ docker system df
## 完整清理
$ docker system prune -a --volumes
```