Docker 容器使用

容器的增删查改、进入容器、看日志、拷文件、导出导入。

Beginner
Key Points日常就六个命令:run / ps / exec / logs / stop / rm;排查问题先 logs,再 exec 进去看。

查看

Bash
docker ps                  # 运行中
docker ps -a               # 含已退出
docker ps -aq              # 只输出 id(便于批量操作)
docker inspect web         # 完整 JSON,含 IP、挂载、环境变量
docker stats               # 实时 CPU/内存/网络

进入容器

Bash
docker exec -it web bash        # 新开一个进程(推荐)
docker exec -it web sh          # 镜像里没有 bash 时
docker attach web               # 接到主进程的 stdin/stdout,慎用:exit 会停掉容器
Prefer docker exec over attach. Exiting an attached session (Ctrl+C / exit) kills the main process and stops the container.

日志

Bash
docker logs web
docker logs -f --tail 100 web     # 跟踪最后 100 行
docker logs --since 10m web       # 最近 10 分钟

docker logs reads the main process's stdout/stderr. If the app writes to a file, you see nothing — containerised apps should log to stdout and let the log driver collect it.

拷贝文件

Bash
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
docker cp ./index.html web:/usr/share/nginx/html/index.html

停止与删除

Bash
docker stop web            # SIGTERM,10 秒后 SIGKILL
docker kill web            # 直接 SIGKILL
docker rm web              # 已停止的容器
docker rm -f web           # 强制删运行中的
docker container prune     # 清掉所有已退出的容器

导出与导入

CommandWhat it doesNote
docker exportFlatten a container to a tarLoses history and metadata
docker importCreate an image from that tarNeeds -c to set CMD
docker saveArchive an image with all layersPreferred for moving images
docker loadRestore a save archiveKeeps tags
Bash
# 搬镜像到没有网络的机器
docker save -o app.tar myapp:1.0
docker load -i app.tar

Friends & Partners