最后修改时间:2019年8月12日
文档版本:1.0
上一章我们已经成功使用docker启动centos镜像,能够进入容器中运行我们想要的服务,但如果我们要把已经部署的服务在另一台机器上实现快速部署,显然不可能重新创建centos容器并一步步安装服务。我们可以把部署好服务的容器打包成镜像,在其他机器上使用创建的镜像进行快速部署。
Docker创建镜像主要有两种方式,第一种是利用commit命令把部署好服务的容器打包成镜像,第二种是使用Dockerfile。
一. 使用commit命令创建镜像
[1]. 启动CentOS镜像并安装httpd服务
# 启动一个CentOS容器,并进入bash
[root@localhost ~]# docker run -it centos /bin/bash
# 安装httpd服务
[root@066c0b5d5696 /]# yum install -y httpd
. . .
. . .
# 往index主页填充内容
[root@066c0b5d5696 /]# echo 'It Works!!' > /var/www/html/index.html
[root@066c0b5d5696 /]# exit
[2]. 把安装好httpd服务的容器打包成镜像
# 把现存的容器打包成镜像
[root@localhost ~]# docker commit 066c0b5d5696 centos_httpd
sha256:55c368fdfd2466d1133fad7c880f928c8bfe6847626c6d27621b2d8f7175af7b
# 查看镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE centos_httpd latest 6c9e4b80dc6f 34 minutes ago 346 MB docker.io/centos latest 9f38484d220f 4 months ago 202 MB
[3]. 使用刚才新建的镜像创建一个新容器,并把80端口映射至本机8080端口,并启动httpd服务
# 加入-d使容器后台运行
[root@localhost ~]# docker run -d -p 8080:80 centos_httpd /usr/sbin/httpd -D FOREGROUND
[4]. 验证服务
(a). 命令行验证
# 使用curl命令验证
[root@localhost ~]# curl 127.0.0.1:8080
It Works!!
(b). 浏览器验证

二. 使用Dockerfile创建镜像
[1]. 创建Dockerfile文件
# 根据需求创建Dockerfile
[root@localhost ~]# vim Dockerfile
FROM centos
RUN yum -y install httpd
RUN echo "It Works!!"; /var/www/html/index.html
EXPOSE 80
CMD ["-D", "FOREGROUND"]
ENTRYPOINT ["/usr/sbin/httpd"]
[2]. 创建镜像
[root@localhost ~]# docker build -t centos_httpd_dockerfile .
Sending build context to Docker daemon 37.89 kB
Step 1/6 : FROM centos
---> 9f38484d220f
Step 2/6 : RUN yum -y install httpd
---> Running in 05b113b7b0b1
. . .
. . .
Removing intermediate container 05b113b7b0b1
Step 3/6 : RUN echo "It Works!!" > /var/www/html/index.html
---> Running in 78323f61b9eb
---> 5bf289c6016c
Removing intermediate container 78323f61b9eb
Step 4/6 : EXPOSE 80
---> Running in f69a5974aa35
---> 7601d5be0d10
Removing intermediate container f69a5974aa35
Step 5/6 : CMD -D FOREGROUND
---> Running in 5459926fef25
---> 8cf45a860cc6
Removing intermediate container 5459926fef25
Step 6/6 : ENTRYPOINT /usr/sbin/httpd
---> Running in 6436117432c1
---> 943737a55650
Removing intermediate container 6436117432c1
Successfully built 943737a55650
# 查看镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE centos_httpd_dockerfile latest 943737a55650 5 minutes ago 346 MB centos_httpd latest fb0b3b7fbbbe 22 minutes ago 346 MB docker.io/centos latest 9f38484d220f 5 months ago 202 MB
[3]. 使用刚才新建的镜像创建一个新容器,并把80端口映射至本机80端口
# 加入-d使容器后台运行
[root@localhost ~]# docker run -d -p 80:80 centos_httpd_dockerfile
# 查看正在运行的容器
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f0193ec51b90 centos_httpd_dockerfile "/usr/sbin/httpd -..." 3 seconds ago Up 1 second 0.0.0.0:80->80/tcp fervent_volhard
[4]. 验证服务
(a). 命令行验证
# 使用curl命令验证
[root@localhost ~]# curl 127.0.0.1
It Works!!
(b). 浏览器验证
