当运行容器时,使用的镜像如果在本地中不存在,docker 就会自动从 docker 镜像仓库中下载,默认是从 Docker Hub 公共镜像源下载。
一、列出镜像列表
可以使用 docker images 来列出本地主机上的镜像。

各个选项说明:
-
**REPOSITORY:**表示镜像的仓库源
-
**TAG:**镜像的标签
-
**IMAGE ID:**镜像ID
-
**CREATED:**镜像创建时间
-
**SIZE:**镜像大小
同一仓库源可以有多个 TAG,代表这个仓库源的不同个版本,如 ubuntu 仓库源里,有 15.10、14.04 等多个不同的版本,我们使用 REPOSITORY:TAG 来定义不同的镜像。所以,我们如果要使用版本为15.10的ubuntu系统镜像来运行容器时,命令如下:

参数说明:
- -i: 交互式操作。
- -t: 终端。
- ubuntu:15.10: 这是指用 ubuntu 15.10 版本镜像为基础来启动容器。
- /bin/bash:放在镜像名后的是命令,这里我们希望有个交互式 Shell,因此用的是 /bin/bash。
如果你不指定一个镜像的版本标签,例如你只使用 ubuntu,docker 将默认使用 ubuntu:latest 镜像。
二、获取一个新的镜像
当我们在本地主机上使用一个不存在的镜像时 Docker 就会自动下载这个镜像。如果我们想预先下载这个镜像,我们可以使用 docker pull 命令来下载它。查找可以下载的ubantu镜像:

下载boystar/ubantu镜像:

三、删除镜像
镜像删除使用 docker rmi 仓库源 命令:

四、创建镜像
当我们从 docker 镜像仓库中下载的镜像不能满足我们的需求时,我们可以通过以下两种方式对镜像进行更改。
- 从已经创建的容器中更新镜像,并且提交这个镜像
- 使用 Dockerfile 指令来创建一个新的镜像
下面演示在已有的容器中更新镜像,Dockerfile 指令的方式会在以后的文章中再说。
更新镜像之前,我们需要使用镜像来创建一个容器。在运行的容器内使用 apt-get update 命令进行更新。在完成操作之后,输入 exit 命令来退出这个容器。此时 ID 为 bd1a5e99ed0d的容器,是按我们的需求更改的容器。我们可以通过命令 docker commit 来提交容器副本。


各个参数说明:
-
-m: 提交的描述信息
-
-a: 指定镜像作者
-
**e218edb10161:**容器 ID
-
runoob/ubuntu:v2: 指定要创建的目标镜像名
我们可以使用 docker images 命令来查看我们的新镜像 runoob/ubuntu:v2:

使用我们的新镜像 runoob/ubuntu 来启动一个容器

五、常见的镜像实例
1、Docker 安装 MySQL

运行mysql

参数说明:
- -p 3306:3306 :映射容器服务的 3306 端口到宿主机的 3306 端口,外部主机可以直接通过 宿主机ip:3306 访问到 MySQL 的服务。
- MYSQL_ROOT_PASSWORD=123456:设置 MySQL 服务 root 用户的密码。
使用docker ps命令查看是否安装成功:

进入mysql客户端:

2、Docker 安装 Node.js
拉取最新版的node.js

运行node容器,--name 指定容器名称

进入容器查看node版本

3、Docker 安装 Redis
拉取最新的redis

运行redis容器,-p 6379:6379:映射容器服务的 6379 端口到宿主机的 6379 端口。外部可以直接通过宿主机ip:6379 访问到 Redis 的服务。

进入redis客户端

4、Docker 安装 Nginx
拉取最新的nginx

运行nginx容器

参数说明:
- --name nginx-test:容器名称。
- -p 8080:80: 端口进行映射,将本地 8080 端口映射到容器内部的 80 端口。
- -d nginx: 设置容器在在后台一直运行。
最后我们可以通过浏览器可以直接访问 8080 端口的 nginx 服务:
