Docker 镜像使用
拉取、查看、打标签、删除镜像,理解 tag 与 digest、清理磁盘。
Key Pointstag 只是指向某个 digest 的可变指针;生产环境用 digest 固定版本,避免「latest 变了」导致的环境漂移。
拉取与查看
Bash
docker pull nginx:1.27-alpine
docker images
docker image inspect nginx:1.27-alpine | head -40
docker history nginx:1.27-alpine # 每层怎么来的tag 与 digest
1.27 is a tag — a movable pointer; sha256:... is a digest that changes only when content changes. Pin by digest in CI to guarantee today's build matches yesterday's.
Bash
docker pull nginx@sha256:0f7e5f1c... # 固定 digest
docker inspect --format='{{index .RepoDigests 0}}' nginx:1.27-alpine打标签与推送
Bash
docker tag myapp:1.0 registry.example.com/team/myapp:1.0
docker tag myapp:1.0 registry.example.com/team/myapp:latest
docker push registry.example.com/team/myapp:1.0One image can carry many tags. Deleting a tag only removes a reference; layers are freed when the last reference goes away.
删除与清理
Bash
docker rmi nginx:1.27-alpine
docker image prune # 悬空镜像(<none>)
docker image prune -a # 所有没被容器使用的镜像
docker system prune -a --volumes # 连卷一起清(危险)| Command | Removes | Safe? |
|---|---|---|
image prune | Dangling images only | Safe |
image prune -a | All unused images | Safe but re-pull needed |
system prune -a | Images + stopped containers + networks | Usually safe |
system prune -a --volumes | Also unused volumes | Danger: data loss |
从容器提交镜像
Bash
docker run -it --name tmp ubuntu:24.04 bash
# 在容器里改点东西,exit
docker commit tmp myimg:snapshotcommit snapshots a container into an image, but it is a black box: nobody knows what changed and it cannot be reproduced. Write a Dockerfile instead.
拉取与查看
Bash
docker pull nginx:1.27-alpine
docker images
docker image inspect nginx:1.27-alpine | head -40
docker history nginx:1.27-alpine # 每层怎么来的tag 与 digest
nginx:1.27 中的 1.27 是 tag,本质是一个可被人为移动的指针;sha256:... 是 digest,内容不变它就不变。CI 里用 digest 拉取,才能保证「今天构建的和昨天一样」。
Bash
docker pull nginx@sha256:0f7e5f1c... # 固定 digest
docker inspect --format='{{index .RepoDigests 0}}' nginx:1.27-alpine打标签与推送
Bash
docker tag myapp:1.0 registry.example.com/team/myapp:1.0
docker tag myapp:1.0 registry.example.com/team/myapp:latest
docker push registry.example.com/team/myapp:1.0同一个镜像可以有多个 tag,删除某个 tag 只是解除引用,不释放空间;只有最后一个引用消失,层才会被回收。
删除与清理
Bash
docker rmi nginx:1.27-alpine
docker image prune # 悬空镜像(<none>)
docker image prune -a # 所有没被容器使用的镜像
docker system prune -a --volumes # 连卷一起清(危险)| 命令 | 清理对象 | 安全性 |
|---|---|---|
image prune | 仅悬空镜像 | 安全 |
image prune -a | 所有未使用镜像 | 安全但要重新拉 |
system prune -a | 镜像+停止的容器+网络 | 通常安全 |
system prune -a --volumes | 还包含未使用的卷 | 危险:会丢数据 |
从容器提交镜像
Bash
docker run -it --name tmp ubuntu:24.04 bash
# 在容器里改点东西,exit
docker commit tmp myimg:snapshotcommit 能把容器当前状态存成镜像,但它是「黑盒快照」:没人知道里面改了什么,也无法重现。正确做法是写 Dockerfile 重建。