Docker 镜像使用

拉取、查看、打标签、删除镜像,理解 tag 与 digest、清理磁盘。

Beginner
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.0
One 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   # 连卷一起清(危险)
CommandRemovesSafe?
image pruneDangling images onlySafe
image prune -aAll unused imagesSafe but re-pull needed
system prune -aImages + stopped containers + networksUsually safe
system prune -a --volumesAlso unused volumesDanger: data loss

从容器提交镜像

Bash
docker run -it --name tmp ubuntu:24.04 bash
# 在容器里改点东西,exit
docker commit tmp myimg:snapshot

commit 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.

Friends & Partners