以构建nginx为例子。实现dockerfile的优化。
FROM centos:7
RUN yum -y install gcc gcc-c++ pcre-devel zlib-devel make
ADD nginx-1.12.2.tar.gz /opt
RUN useradd -M -s /sbin/nologin nginx
WORKDIR /opt/nginx-1.12.2
RUN ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module
RUN make && make install
RUN ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin
EXPOSE 80
EXPOSE 443
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
docker build -t nginx:v1 .
#构建镜像
docker images
#查看镜像大小
注意!!如果输入&>/dev/null,需要确保执行的命令时没有问题的,不然可以选择 1>/dev/null,错误的输出还是会打印到页面,方便查看。
重新修改dockerfile文件
FROM centos:7
RUN yum -y install gcc gcc-c++ pcre-devel zlib-devel make &>/dev/null && yum clean all
ADD nginx-1.12.2.tar.gz /opt
RUN useradd -M -s /sbin/nologin nginx
WORKDIR /opt/nginx-1.12.2
RUN ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module &>/dev/null
RUN make && make install &>/dev/null
RUN rm -rf /opt/nginx-1.12.2
RUN ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin
EXPOSE 80
EXPOSE 443
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
重新构建查看大小
docker build -t nginx:v2 .
docker images
因为每一条命令都会构建一层镜像,较少命令的使用,相当于减少构建的层数。
修改Dockerfile文件
FROM centos:7
ADD nginx-1.12.2.tar.gz /opt
WORKDIR /opt/nginx-1.12.2
RUN useradd -M -s /sbin/nologin nginx && yum -y install gcc gcc-c++ pcre-devel zlib-devel make && ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module && make && make install &>/dev/null && yum clean all && rm -rf /opt/nginx-1.12.2 &&ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin
EXPOSE 80
EXPOSE 443
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
重新构建查看大小
docker build -t nginx:v3 .
docker images
重新编写Dockerfile文件
FROM centos:7 as ydq
ADD nginx-1.12.2.tar.gz /opt
WORKDIR /opt/nginx-1.12.2
RUN useradd -M -s /sbin/nologin nginx && yum -y install gcc gcc-c++ pcre-devel zlib-devel make && ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module && make && make install &>/dev/null && yum clean all && rm -rf /opt/nginx-1.12.2 &&ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin
FROM centos:7
EXPOSE 80
EXPOSE 443
VOLUME ["/usr/local/nginx/html"]
COPY --from=ydq /usr/local/nginx /usr/local/nginx
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
查看重新构建的大小
docker build -t nginx:v4 .
docker images
以下不是dockerfile优化,不过多解释,可理解为基于模板创建镜像,
wget http://download.openvz.org/template/precreated/debian-7.0-x86-minimal.tar.gz
#下载debian压缩包
docker import debian-7.0-x86-minimal.tar.gz -- debian:v1
dockerfile优化主要可以从几点切入
1、减少标准输出的内容,使用 yum clean all 清除缓存,删除上传的压缩包
2、减少使用RUN命令,能合并尽量合并
3、可以使用多阶段构建镜像(不过需要17版本之后才支持)