上一篇:Docker的那些事儿—基于运行的容器状态生成新的镜像,即docker commit(10)
前面无论是说到测试镜像还是Base镜像,一直在反复提到一个词:Dockerfile。
下面我们演示如何根据Dockerfile构建镜像:
1、创建mydockerfile目录
2、进入mydockerfile目录,创建Dockerfile文件,内容如下:

3、使用docker build -t ubuntu-ssh-dockerfile:v1.0 .构建镜像
-t 指定新的镜像名字,:v1.0为镜像指定tag,指定Dockerfile文件所在路径。
注意:Dockerfile文件名不一定必须叫Dockerfile。如果你的Dockerfile文件名不是Dockerfile,需要加-f参数指定你的Dockerfile文件。如果没有-f参数,docker默认去寻找Dockerfile这个文件


分析上述docker build的构建过程:
Sending buildcontext to Docker daemon 2.048kB
Step 1/3: From ubuntu #获取ubuntu镜像
---> 00fd29ccc6f1 #镜像ID为00fd29ccc6f1
Step 2/3 : RUNapt-get update && apt-get install -y openssh-server
---> Running in 18c5f04edaed #以00fd29ccc6f1镜像,运行临时容器,ID为18c5f04edaed
#开始在容器内执行apt-get update命令
Get:1http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Get:2http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB]
...
...
#开始在容器内执行apt-get install -y openssh-server命令
Reading packagelists...
Reading packagelists...
Buildingdependency tree...
Reading stateinformation...
The followingadditional packages will be installed:
...
...
Running hooks in/etc/ca-certificates/update.d...
done.
Processingtriggers for systemd (229-4ubuntu21) ...
Removing
intermediate container 18c5f04edaed #删除临时容器
---> 4296009b93f2#生成新的镜像,镜像ID为4296009b93f2
Step 3/3: CMD ["/bin/bash"]
---> Running in 396ff094f760 #以4296009b93f2镜像,运行新的临时容器
Removing
intermediate container 396ff094f760 #删除临时容器
---> 91bf8ac8749e#生成新的镜像,镜像ID为91bf8ac8749e
Successfully built91bf8ac8749e #构建出最终的镜像
Successfully tagged ubuntu-ssh-dockerfile:v1.0 #为镜像打上标签
镜像是一层层叠加起来的,这和我们之前讲到的是一致的。
查询本地构建的镜像

验证新镜像


从docker history,也印证了我们上述的分析(从下向上看)
继续修改Dockerfile文件内容如下:


为啥这次构建这么快?原因是docker在build镜像时使用了缓存。第二步Using cache就是。可以对比下第一次的构建过程。
如果不想使用缓存,可以加--no-cache参数

如果不想每一步创建的临时容器都删除,可以加--rm=false。默认该参数是true



可见第4、5步创建的临时容器并没有被删除掉。其他参数请参考docker build --help。
下一篇:Docker的那些事儿—docker commit与docker build比较(12)

网友评论