Dockerfile 是一个文本文件,记录了镜像构建的所有步骤。
创建Dockerfile
用 Dockerfile 创建上节的 ubuntu-with-vi,其内容则为:
下面我们运行 docker build 命令构建镜像并详细分析每个细节。
root@ubuntu:~# pwd ①
/root
root@ubuntu:~# ls ②
Dockerfile
root@ubuntu:~# docker build -t ubuntu-with-vi-dockerfile . ③
Sending build context to Docker daemon 32.26 kB ④
Step 1 : FROM ubuntu ⑤
---> f753707788c5
Step 2 : RUN apt-get update && apt-get install -y vim ⑥
---> Running in 9f4d4166f7e3 ⑦
......
Setting up vim (2:7.4.1689-3ubuntu1.1) ...
---> 35ca89798937 ⑧
Removing intermediate container 9f4d4166f7e3 ⑨
Successfully built 35ca89798937 ⑩
root@ubuntu:~#
① 当前目录为 /root。
② Dockerfile 准备就绪。
③ 运行 docker build 命令,-t 将新镜像命名为 ubuntu-with-vi-dockerfile,命令末尾的 . 指明 build context 为当前目录。Docker 默认会从 build context 中查找 Dockerfile 文件,我们也可以通过 -f 参数指定 Dockerfile 的位置。
④ 从这步开始就是镜像真正的构建过程。 首先 Docker 将 build context 中的所有文件发送给 Docker daemon。build context 为镜像构建提供所需要的文件或目录。
Dockerfile 中的 ADD、COPY 等命令可以将 build context 中的文件添加到镜像。此例中,build context 为当前目录 /root,该目录下的所有文件和子目录都会被发送给 Docker daemon。
所以,使用 build context 就得小心了,不要将多余文件放到 build context,特别不要把 /、/usr 作为 build context,否则构建过程会相当缓慢甚至失败。
⑤ Step 1:执行 FROM,将 ubuntu 作为 base 镜像。
ubuntu 镜像 ID 为 f753707788c5。
⑥ Step 2:执行 RUN,安装 vim,具体步骤为 ⑦、⑧、⑨。
⑦ 启动 ID 为 9f4d4166f7e3 的临时容器,在容器中通过 apt-get 安装 vim。
⑧ 安装成功后,将容器保存为镜像,其 ID 为 35ca89798937。
这一步底层使用的是类似 docker commit 的命令。
⑨ 删除临时容器 9f4d4166f7e3。
⑩ 镜像构建成功。
通过 docker images 查看镜像信息。
值得一提的是,Docker 会缓存已有镜像的镜像层,构建新镜像时,如果某镜像层已经存在,就直接使用,无需重新创建。
这就是这个扩展镜像的过程。