docker构建镜像的方式有两种,一种是经过 docker commit 命令构建,另外一种是经过 Dockerfile 构建文件构建。下面分别经过两种方式介绍这两种构建方式。docker
接下来,咱们会分别采用上述的两种方式构建带有vim命令的centos镜像。vim
咱们先查看下当前的环境。在本地docker仓库中如今有一个centos 7.4.1708 的镜像,若是没有请先拉取。centos
如今以交互的方式运行该centos7镜像bash
docker run -it centos:7.4.1708
-it 参数ui
这个参数是以交互方式运行centos镜像的意思,也就是咱们进入到该centos7的容器中(也就是该用户空间中),这里须要注意一点的是,咱们的容器是运行在宿主主机上的,也就是说容器的运行内核是宿主主机的内核(bootfs)。这里,若是咱们在centos镜像中运行 uname 命令,这里显示的是docker宿主主机的内核版本号。centos7
接下来,咱们以交互方式运行下centos容器的vim命令,结果base image是没有预装vim命令的。spa
咱们看到,在命令行的左边,出现了一个 74c83be9fd78 ,这个是在docker engine运行的容器ID,咱们在宿主主机上能够经过命令,查看当前在docker引擎中运行的全部容器。命令行
docker ps
下方的就是咱们运行中的centos容器了。3d
这种方式构建装有vim命令的新的centos镜像须要完成如下三个步骤:code
(1)运行容器。前面已经启动了centos容器
(2)修改容器,须要在运行的容器中安装vim命令
(3)将修改后的容器保存为新的镜像
经过交互模式进入须要新修改的centos7容器,运行yum命令安装vim命令
yum install -y vim
安装后,从新运行vim检查是否安装成功。
在新窗口中查看当前运行的容器
执行commit命令将容器保存为新的镜像,050704f7c569 是运行的容器的ID,centos7-vim-by-commit是新镜像的名字,1.0.0是版本号
docker commit 050704f7c569 centos7-vim-by-commit:1.0.0
commit成功 后,查看下当前仓库中的docker镜像,多了一个centos7-vim-by-commit,tag是1.0.0的镜像
咱们运行该镜像
docker run -it centos7-vim-by-commit:1.0.0
发现vim命令是能够运行的。
除了能够用commit方式构建镜像,咱们还能够用 Dockerfile(推荐方法)构建镜像。
首先,咱们在/root中建立一个目录 first-dockerfile , 该目录做为咱们构建镜像的build context
[root@localhost first-dockerfile]# pwd /root/first-dockerfile
咱们在该目录下建立一个名字为Dockerfile的文件,该文件是docker构建镜像的脚本
FROM centos:7.4.1708 RUN yum install -y vim
准备就绪后,在first-dockerfile目录下运行,开始构建新的镜像
docker build -t centos7-vim-by-dockerfile:1.0.0 .
build命令,-t参数将新镜像命名为centos7-vim-by-dockerfile,tag是1.0.0。命令最后的 . ,指明当前目录为build context,默认状况下从build context中查找Dockerfile文件
执行build命令后,开始执行构建过程
[root@localhost first-dockerfile]# docker build -t centos7-vim-by-dockerfile:1.0.0 . Sending build context to Docker daemon 2.048kB Step 1/2 : FROM centos:7.4.1708 ---> 295a0b2bd8ea Step 2/2 : RUN yum install -y vim ---> Running in 121ba3c1492c ............ 省略安装过程 Complete! Removing intermediate container 121ba3c1492c ---> 6148376c2a1f Successfully built 6148376c2a1f Successfully tagged centos7-vim-by-dockerfile:1.0.0
咱们能够经过查看本地镜像和镜像分层的方式验证。
查看本地镜像
[root@localhost first-dockerfile]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE centos7-vim-by-dockerfile 1.0.0 6148376c2a1f 24 minutes ago 350MB centos7-vim-by-commit 1.0.0 bda9b5d82a72 2 days ago 350MB centos 7.4.1708 295a0b2bd8ea 4 weeks ago 197MB hello-world latest 4ab4c602aa5e 2 months ago 1.84kB
查看镜像分层
[root@localhost first-dockerfile]# docker history 6148376c2a1f IMAGE CREATED CREATED BY SIZE COMMENT 6148376c2a1f 36 minutes ago /bin/sh -c yum install -y vim 153MB 295a0b2bd8ea 4 weeks ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B <missing> 4 weeks ago /bin/sh -c #(nop) LABEL name=CentOS Base Im… 0B <missing> 4 weeks ago /bin/sh -c #(nop) ADD file:d6a1da927f0b7a710… 197MB
docker history命令会显示镜像的构建历史。