主题
Docker 镜像(Image)
镜像是用于创建容器的只读模板,包含应用程序、依赖及运行环境。
镜像通常从镜像仓库(Registry)拉取,或通过 Dockerfile 在本地构建。
docker image 是镜像管理命令组,部分命令可以简写,例如 docker image ls 等价于 docker images。
常用命令
bash
# 获取与查看
docker image pull nginx:latest # 拉取指定镜像
docker image ls # 查看本地镜像
docker image inspect nginx:latest # 查看镜像详细信息
docker image history nginx:latest # 查看镜像构建历史
# 构建与发布
docker image build -t my-app:latest . # 使用当前目录构建镜像
docker image build --no-cache -t my-app:latest . # 不使用缓存构建镜像
docker image tag my-app:latest registry.example.com/my-app:1.0 # 添加镜像标签
docker image push registry.example.com/my-app:1.0 # 推送镜像到仓库
# 删除与清理
docker image rm my-app:latest # 删除指定镜像标签,必要时删除镜像
docker image prune # 清理悬空镜像(dangling)
docker image prune -a # 清理所有未被容器使用的镜像
docker image prune -af # 强制清理所有未被容器使用的镜像,不询问确认仓库认证
拉取私有镜像或推送镜像时,通常需要先登录对应的镜像仓库。
bash
docker login # 登录 Docker Hub
docker logout # 退出 Docker Hub
docker login registry.example.com # 登录指定镜像仓库
docker logout registry.example.com # 退出指定镜像仓库构建镜像(build)
bash
# 命令格式
docker image build [OPTIONS] PATH| 选项 | 作用 |
|---|---|
-t / --tag | 指定镜像名称和标签 |
-f / --file | 指定 Dockerfile 路径 |
--no-cache | 构建时不使用缓存 |
--pull | 尝试拉取较新的基础镜像 |
--build-arg | 传递 Dockerfile 构建参数 |
--platform | 指定目标平台,如 linux/amd64 |
常用示例:
bash
# 使用当前目录的 Dockerfile 构建
docker image build -t my-app:1.0 .
# 指定 Dockerfile
docker image build -f Dockerfile.prod -t my-app:1.0 .
# 不使用缓存并检查基础镜像更新
docker image build --no-cache --pull -t my-app:1.0 .
# 指定目标平台
docker image build --platform linux/amd64 -t my-app:1.0 .其中 . 表示当前目录作为构建上下文(Build Context),并不单纯表示 Dockerfile 所在目录。
清理构建缓存
bash
docker builder prune # 清理悬空构建缓存
docker builder prune -a # 清理所有未使用的构建缓存
docker builder prune -f # 清理悬空构建缓存,不询问确认镜像标签(Tag)
镜像通常使用以下格式:
text
[REGISTRY/]REPOSITORY[:TAG]例如:
text
nginx:latest
nginx:1.27
registry.example.com/my-app:1.0REGISTRY:镜像仓库地址,省略时通常使用 Docker Hub。REPOSITORY:镜像仓库名称。TAG:镜像标签,省略时默认使用latest。
latest 只是普通标签,不代表一定是最新版本。
bash
docker image tag my-app:latest my-app:1.0 # 为已有镜像添加标签tag 不会复制镜像内容,只是创建新的镜像引用。
备份与恢复
使用 save / load 导出和导入镜像,保留镜像层及标签等信息。
bash
# 备份镜像
docker image tag my-app:latest my-app:2.7.2 # 添加版本标签
docker image save -o my-app_2.7.2.tar my-app:2.7.2 # 导出镜像到 tar 文件
# 恢复镜像
docker image load -i my-app_2.7.2.tar # 从 tar 文件导入镜像
# 查看恢复结果
docker image ls my-app也可以通过管道压缩备份文件:
bash
# 压缩备份
docker image save my-app:2.7.2 | gzip > my-app_2.7.2.tar.gz
# 解压并恢复
gunzip -c my-app_2.7.2.tar.gz | docker image load常用命令区别
| 命令 | 作用 |
|---|---|
pull | 从镜像仓库拉取镜像 |
build | 根据 Dockerfile 构建镜像 |
ls | 查看本地镜像 |
inspect | 查看镜像详细信息 |
history | 查看镜像构建历史 |
tag | 为已有镜像添加标签 |
push | 将镜像推送到仓库 |
rm | 删除镜像引用,必要时删除镜像 |
prune | 清理无用镜像 |
save | 导出镜像为归档文件 |
load | 从归档文件导入镜像 |
注意:
- 镜像(Image)是模板,容器(Container)是镜像的运行实例。
- 删除镜像不会自动删除容器,正在被容器使用的镜像通常无法直接删除。
docker image save只备份镜像,不包含容器运行数据、Volume 或数据库数据。docker image prune -af可能清理以后还需要使用的镜像,执行前应确认。
