Docker 入门(三):镜像归档与容器生命周期
本篇继续介绍 Docker 的镜像和容器命令,重点解决三个问题:如何给镜像打标签、如何查看镜像构建历史、如何把镜像导出并在另一台机器恢复,以及如何管理容器生命周期。
镜像标签:docker tag
标签只是给同一个镜像 ID 增加一个新的名称,不会复制镜像层:
bash
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
docker tag hello-world:latest registry.example.com/demo/hello-world:1.0
推送私有仓库前,通常先用 docker tag 补上仓库地址和版本号。
查看镜像历史:docker history
bash
docker history nginx:latest
docker history --no-trunc nginx:latest
该命令可以查看镜像各层的创建命令、大小和时间,排查镜像体积或 Dockerfile 分层问题时很有帮助。
导出与导入镜像
使用 docker save 将一个或多个镜像保存为 tar 文件:
bash
docker save -o hello-world.tar hello-world:latest
在目标机器上使用 docker load 恢复:
bash
docker load -i hello-world.tar
docker image ls hello-world
save/load 面向镜像,适合离线迁移并保留镜像层和标签;不要把它与面向容器文件系统的 docker export/import 混用。
容器生命周期
创建并运行
bash
docker run --name demo -d nginx:latest
docker run 会创建容器并启动主进程。常用选项包括 --name、-d(后台运行)、-p(端口映射)、-v(挂载目录)和 --rm(退出后自动删除)。
启动、重启和停止
bash
docker start demo
docker restart demo
docker stop demo
stop 会先发送正常终止信号,等待超时后再强制结束;kill 会立即发送信号,适合处理无法正常停止的异常容器。
查看和清理
bash
docker ps
docker ps -a
docker logs -f demo
docker rm demo
删除容器前应确认其中没有未持久化的数据。运行中的容器不能直接删除,必要时可以使用 docker rm -f demo,但生产环境应先定位原因再强制清理。
小结
tag 管理镜像名称,history 解释镜像分层,save/load 完成离线迁移;run/start/stop/restart/kill/ps/rm 则覆盖了容器从创建到清理的主要生命周期。