Dockerfile方式创建一个http服务器

这个http服务器镜像的创建真是一波三折。
首先看一下最终的目录结构:

1
2
3
4
5
.
├── Dockerfile
└── run-httpd.sh

0 directories, 2 files

只有2个文件。
现在查看Dockerfile文件的内容。

1
2
3
4
5
6
7
8
9
10
11
FROM centos:latest 
MAINTAINER by huangbin
RUN yum -y update; yum clean all
RUN yum -y install httpd && yum clean all
RUN touch /var/www/html/index.html
RUN echo "Hello,Docker" >>/var/www/html/index.html
EXPOSE 80
#Simple startup script to avoid some issues observed with container restart
ADD run-httpd.sh /run-httpd.sh
RUN chmod -v +x /run-httpd.sh
CMD ["/run-httpd.sh"]

现在解读一下指令:

FROM

该指令指出,即将创建的镜像是以什么镜像为基础创建的。

MAINTAINER

该指令是负责给该镜像进行注释的,添加一些信息。

RUN

该指令负责在创建镜像的时候,运行后面的指令。注意是镜像创建的时候,而不是容器创建时。

ADD

该指令复制一个文件到镜像中。与COPY不同的是,该指令会对targz这种自行解压解包。

CMD

该指令会在容器创建的时候执行,注意,是容器,而不是镜像。这个指令会被容器创建时传入的指令覆盖(当然,如果没有的话,就不会覆盖)。

然后来看run-httpd.sh

1
2
3
4
5
6
#!/bin/bash 
# Make sure we're not confused by old, incompletely-shutdown httpd
# context after restarting the container. httpd won't start correctly
# if it thinks it is already running.
rm -rf /run/httpd/*
exec /usr/sbin/apachectl -D FOREGROUND

可以看到,只是单纯的将安装的http服务启动起来。
最后用下面这个命令启动:

1
docker run -d -p 8080:80 http:centos

上面的命令将本机的8080端口映射到容器暴露的80端口。
然后通过curl命令可以访问本机的8080端口得到Hello,Docker的返回结果。