Auto-sync: 2026-04-22 08:02

This commit is contained in:
2026-04-22 08:02:59 +08:00
parent de096f2f88
commit 143d1fd105
62 changed files with 5232 additions and 1268 deletions

View File

@@ -0,0 +1,143 @@
---
title: "Docker容器生命周期管理"
type: concept
tags: [docker, container, lifecycle, operations]
date: 2026-04-22
---
# Docker容器生命周期管理
## Definition
Docker 容器生命周期管理是指对容器的创建、启动、停止、删除等各阶段进行规范操作的过程,是 Home Server 日常运维的基础技能。
## Lifecycle States
```
created → starting → running → stopping → stopped → removing → removed
↑ ↓
└────────── restarting ←──────┘
```
## Core Commands
### 查看
```bash
# 查看运行中的容器
docker ps
# 查看所有容器(包括已停止)
docker ps -a
# 查看特定应用的容器
docker ps -a | grep portainer
# 查看容器详细信息
docker inspect <container_name_or_id>
```
### 启动与停止
```bash
# 停止运行中的容器
docker stop <container_name_or_id>
# 强制停止SIGKILL8秒超时后强制终止
docker kill <container_name_or_id>
# 启动已停止的容器
docker start <container_name_or_id>
# 重启容器stop + start
docker restart <container_name_or_id>
```
### 删除
```bash
# 删除已停止的容器
docker rm <container_name_or_id>
# 强制删除运行中的容器(先停止再删除)
docker rm -f <container_name_or_id>
# 删除所有已停止的容器
docker container prune
# 一条命令停止并删除
docker stop <container_name> && docker rm <container_name>
```
### 完整重建流程(以 Portainer 为例)
```bash
# 1. 停止容器
docker stop portainer
# 2. 删除容器
docker rm portainer
# 3. (可选) 删除数据卷
docker volume ls | grep portainer
docker volume rm portainer_data
# 4. (可选) 删除网络
docker network ls | grep portainer
docker network rm portainer_network
# 5. 重新部署
docker compose up -d
```
## Lifecycle Management Best Practices
### 1. Always Stop Before Remove
删除运行中的容器前应先停止,否则需要使用 `-f` 强制删除。强制删除可能导致数据丢失或不一致状态。
### 2. Check Dependencies
删除容器前检查是否有其他容器依赖它:
```bash
docker inspect <container> --format '{{.HostConfig.Links}}'
```
### 3. Use --filter for Bulk Operations
```bash
# 删除所有已停止的容器
docker container prune
# 删除所有 portainer 相关容器
docker rm $(docker ps -a --filter "name=portainer" -q)
# 删除所有退出的容器
docker rm $(docker ps -a --filter "status=exited" -q)
```
### 4. Label-based Lifecycle
给容器打标签以便批量管理:
```bash
# 创建时打标签
docker run --label "env=production" --label "app=web" nginx
# 按标签查找
docker ps --filter "label=env=production"
```
## Data Persistence
容器删除后,**绑定挂载**bind mount的数据仍然保留但**匿名卷**anonymous volume可能丢失。使用命名卷named volume确保数据持久化
```yaml
volumes:
- portainer_data:/data # 命名卷,删除容器后数据保留
# vs
volumes:
- /data # 匿名卷,不推荐
```
## Related Concepts
- [[Docker卷]] — 容器数据的持久化机制
- [[Docker Network]] — 容器的网络连接生命周期
- [[Docker Compose]] — 多容器应用的声明式生命周期管理
- [[Docker堆栈]] — 多容器协同工作栈的整体生命周期
## Related Entities
- [[Portainer]] — 需要生命周期管理的典型容器应用
- [[Docker]] — 生命周期管理的底层平台
## See Also
- [[如何删除旧的废弃的docker-container-volume]] — Portainer 重装的完整实操记录