006_制作第一个Docker镜像

Docker 镜像
镜像是 Docker 容器的基石,容器是镜像的运行实例,有了镜像才能启动容器 (不明白为啥请看 “Docker 运行流程” 章节) ,对于 Docker 用户来说 了, 最好的情况是不需要自己创建镜像,几乎所有常用的镜像都有现成 Docker 官方镜像或其他爱好者创建的镜像,只需要稍微配置就可以直接使用,使用现成的好处 除了省去自己做镜像的工作量外,更重要的是可以利用前人的经验,特别是 官方镜像,因为 Docker 的工程师知道如何更好的在容器中运行软件; 但是,在公司的话,肯定会构建自己业务的镜像的;


最小的镜像 hello-world
hello-world 是 Docker 官方提供的一个测试镜像,用来验证 Docker 是否安装成功;

docker pull 从 Docker Hub 下载
docker images hello-world 查看镜像 hello-world 的信息
docker run hello-world 运行镜像 hello-world 的容器

006_制作第一个Docker镜像
006_制作第一个Docker镜像
006_制作第一个Docker镜像

006_制作第一个Docker镜像

运行过上边的命令肯定特别想知道 镜像包含哪些内容吧,请继续往下看
首先,咱们的先知道镜像是怎么做出来的,做镜像需要哪些东西,此镜像的作用是啥,是吧???


Docker 构建镜像的方法
1. docker commit 命令
2. Dockerfile 文件构建


docker commit
docker commit 命令是创建新镜像最直观的方法,过程包含3个步骤
1. 运行容器
2. 修改容器
3. 将容器保存为新的镜像

1. 运行容器
006_制作第一个Docker镜像
006_制作第一个Docker镜像

2. 修改容器
安装 vim
006_制作第一个Docker镜像
006_制作第一个Docker镜像

3. 将容器保存为新的镜像
在新窗口中查看当前运行的容器
006_制作第一个Docker镜像
006_制作第一个Docker镜像
pedantic_wright 是 Docker 为容器随机分配的名字

执行 docker commit 命令将容器保存为镜像, 新镜像名为 ubuntu_vim
006_制作第一个Docker镜像
006_制作第一个Docker镜像

查看新镜像的属性
006_制作第一个Docker镜像
006_制作第一个Docker镜像

从新镜像启动容器,验证 vim 已经可以用了
006_制作第一个Docker镜像
006_制作第一个Docker镜像

以上演示了如何用 docker commit 创建新镜像,然而, Docker 并不建议用户通过这种方式构建镜像

咱们来分析一下:
这是一种手工创建镜像的方式,容易出错,效率低且可重复性弱,比如在 debian base 镜像中也加入vim ,还要重复前面的所有步骤;

注意: 即便.使用 Dockerfile (推荐方式) 构建镜像,底层也是 docker commit 一层层构建新镜像的; 学习 docker commit 能够帮助我们更加深入理解构建过程和镜像的分层结构;



使用 Dockerfile 构建第一个镜像
实现输出一段话

0) 环境
006_制作第一个Docker镜像
006_制作第一个Docker镜像

1)dockerfile 是镜像的描述文件,定义了如何构建 Docker 镜像,Dockerfile 的语法简洁且可读性强,下面看一个最简单的 Dockerfile 示例

from centos
copy hello /
RUN chmod +x /hello
cmd /hello
解释:
from centos 指定基础镜像
copy hello / 将文件 hello 复制到镜像的根目录
RUN chmod +x /hello 为 hello 添加执行权限
cmd ["/hello"] 容器启动时,执行 /hello(其实也可以写成 “cmd /hello”)


2)这里用一个可执行的文件说吧,就是下面这货( 就这么简单,你没看错 )

hello
#!/bin/bash
echo " bu tai ben "

3)创建镜像
命令用法:

docker build -t 指定tag标签,即镜像名    PATH( . 指明 build context 为当前目录,也可通过 -f 指定 Dockerfile 的位置 )

docker build -t hello .


4)启动镜像查看结果
006_制作第一个Docker镜像
006_制作第一个Docker镜像

5)查看镜像分层结构
docker history 会显示镜像的构建历史,也就是 Dockerfile 的执行过程;
006_制作第一个Docker镜像
006_制作第一个Docker镜像

总结
docker pull 从 Docker Hub 下载
docker images hello-world 查看镜像 hello-world 的信息
docker run hello-world 运行镜像 hello-world 的容器
docker run hello 根据一个镜像运行一个容器(容器的任务执行完毕后,自动关闭容器)
docker run -it hello 根据一个镜像运行一个容器,并且进入到容器中(此容器需要一直运行)
docker run -it hello /bin/bash 根据一个镜像运行一个容器,并且进入到容器中
docker exec -it ab9afee92f9d /bin/bash 进入到一个正在运行的容器中
docker inspect hello 查看名为 hello 镜像的信息
docker build -t hello . 创建镜像
docker history 显示镜像的构建历史