Docker 容器使用
容器的增删查改、进入容器、看日志、拷文件、导出导入。
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 # 清掉所有已退出的容器导出与导入
| Command | What it does | Note |
|---|---|---|
docker export | Flatten a container to a tar | Loses history and metadata |
docker import | Create an image from that tar | Needs -c to set CMD |
docker save | Archive an image with all layers | Preferred for moving images |
docker load | Restore a save archive | Keeps tags |
Bash
# 搬镜像到没有网络的机器
docker save -o app.tar myapp:1.0
docker load -i app.tar查看
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 会停掉容器优先用
docker exec,不要用 attach。attach 退出(Ctrl+C / exit)会把主进程一起带走,容器直接停。日志
Bash
docker logs web
docker logs -f --tail 100 web # 跟踪最后 100 行
docker logs --since 10m web # 最近 10 分钟docker logs 读的是主进程的 stdout/stderr。应用把日志写进文件而不是标准输出,就看不到——容器里的应用应当输出到 stdout,由日志驱动负责收集。
拷贝文件
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 # 清掉所有已退出的容器导出与导入
| 命令 | 作用 | 说明 |
|---|---|---|
docker export | 把容器拍平成 tar | 丢失历史与元数据 |
docker import | 从 tar 建镜像 | 要用 -c 指定 CMD |
docker save | 打包镜像含所有层 | 搬镜像首选 |
docker load | 还原 save 的包 | 保留 tag |
Bash
# 搬镜像到没有网络的机器
docker save -o app.tar myapp:1.0
docker load -i app.tar