Docker 镜像相关命令介绍与示例

Docker 镜像是容器的基础,包含了运行应用所需的所有文件和依赖。以下是常用的 Docker 镜像命令及其示例:

1. 查看镜像列表

bash 复制代码
docker images

示例输出:

复制代码
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
ubuntu        latest    1d622ef86b13   2 weeks ago    72.9MB
nginx         alpine    6efc2a5a0b54   3 weeks ago    23.5MB

选项:

  • -a:显示所有镜像(包括中间层镜像)
  • --no-trunc:显示完整的镜像ID
  • -q:只显示镜像ID

2. 拉取镜像

bash 复制代码
docker pull [选项] <镜像名>[:标签]

示例:

bash 复制代码
docker pull ubuntu:20.04
docker pull nginx:alpine

3. 搜索镜像

bash 复制代码
docker search [选项] <关键词>

示例:

bash 复制代码
docker search mysql
docker search --limit 5 redis

4. 删除镜像

bash 复制代码
docker rmi [选项] <镜像名或ID>

示例:

bash 复制代码
docker rmi ubuntu:20.04
docker rmi 1d622ef86b13

选项:

  • -f:强制删除

5. 查看镜像详情

bash 复制代码
docker inspect <镜像名或ID>

示例:

bash 复制代码
docker inspect nginx

6. 构建镜像

bash 复制代码
docker build [选项] <上下文路径>

示例:

bash 复制代码
docker build -t myapp:v1 .
docker build -f Dockerfile.dev -t myapp:dev .

7. 给镜像打标签

bash 复制代码
docker tag <源镜像> <新镜像名>:<标签>

示例:

bash 复制代码
docker tag nginx:alpine myregistry.com/nginx:prod

8. 保存镜像为文件

bash 复制代码
docker save -o <文件名>.tar <镜像名>

示例:

bash 复制代码
docker save -o nginx.tar nginx:alpine

9. 从文件加载镜像

bash 复制代码
docker load -i <文件名>.tar

示例:

bash 复制代码
docker load -i nginx.tar

10. 查看镜像历史

bash 复制代码
docker history <镜像名>

示例:

bash 复制代码
docker history ubuntu:20.04

11. 清理无用镜像

bash 复制代码
docker image prune [选项]

示例:

bash 复制代码
docker image prune -a  # 删除所有未被容器使用的镜像
docker image prune -a --filter "until=24h"  # 删除24小时前创建的无用镜像

12. 导出和导入镜像

bash 复制代码
# 导出
docker export <容器ID> > container.tar

# 导入
docker import container.tar new-image-name:tag

实际使用示例

  1. 拉取并运行一个Nginx容器:
bash 复制代码
docker pull nginx:alpine
docker run -d -p 8080:80 --name my-nginx nginx:alpine
  1. 构建自定义镜像:
bash 复制代码
# 假设当前目录有Dockerfile
docker build -t my-webapp:v1 .
docker run -p 5000:5000 my-webapp:v1
  1. 备份和恢复镜像:
bash 复制代码
docker save -o backup.tar nginx:alpine ubuntu:20.04
docker load -i backup.tar
  1. 清理空间:
bash 复制代码
# 删除所有未被使用的镜像
docker image prune -a
相关推荐
爱吃香菜的初学者2 小时前
十四.Linux——消息队列
linux·运维·开发语言
Lvan的前端笔记8 小时前
docker:每个前端项目一个 Nginx 容器还是只有一个Nginx容器
前端·nginx·docker
姜鱼问生8 小时前
Nginx 缓存命中率监控:从 X-Cache-Status 到实时统计
运维·nginx·缓存
Apipi*9 小时前
30天速通Linux 第六章信号及信号处理
linux·运维·信号处理
运维行者_10 小时前
网络性能监控怎么做?从自动发现到根因分析的4个环节
运维·服务器·网络·人工智能·支持向量机
此时不提桶,更待何时11 小时前
06-14-A-Kafka集群运维与迁移实战详解
运维·kafka
IT研究所12 小时前
AI-ITR平台如何减少客户问题反复升级?
大数据·运维·人工智能·低代码·自然语言处理·安全架构·企微
AIgorithmGEEK12 小时前
[Linux]从手写报头到内核套路:序列化、反序列化与自定义协议全链路
linux·运维·服务器·网络·序列化·反序列化
Nil20813 小时前
leetcode 139单词拆分
linux·运维·服务器
Starry-sky(jing)13 小时前
BUG: unable to handle kernel paging request 完整排查:dmesg 四要素与三路定罪
linux·运维·服务器·内核·排障