无优化构建nginx镜像
mkdir /nginx
vim dockerfile
FROM centos:7 //基于centos:7镜像
RUN yum install -y gcc pcre pcre-devel devel zlib-devel make //安装依赖环境
ADD nginx-1.15.9.tar.gz /mnt //将源码复制到指定目录,并解压
WORKDIR /mnt/nginx-1.15.9 //为下面的指令指定执行目录
RUN sed -i 's/CFLAGS="$CFLAGS -g"/#CFLAGS="$CFLAGS -g"/g' auto/cc/gcc //关闭Debug调试
RUN ./configure --prefix=/usr/local/nginx //安装编译
RUN make
RUN make install
EXPOSE 80
VOLUME ["/usr/local/nginx/html"] //指定挂载点
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"] //为了保持nginx的容器不退出,关闭nginx后台运行
#上传压缩包
docker build -t nginx:new . //使用当前目录下的文件构建标签为nginx:new的镜像
优化一:不需要输出的指令丢入/dev/null
FROM centos:7
RUN yum install -y gcc pcre pcre-devel devel zlib-devel make &> /dev/null && yum clean all
ADD nginx-1.12.2.tar.gz /mnt
WORKDIR /mnt/nginx-1.12.2
RUN sed -i 's/CFLAGS="$CFLAGS -g"/#CFLAGS="$CFLAGS -g"/g' auto/cc/gcc
RUN ./configure --prefix=/usr/local/nginx &> /dev/null
RUN make &> /dev/null
RUN make install &> /dev/null
RUN rm -rf /mnt/nginx-1.12.2 //删除不需要的文件
EXPOSE 80
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx""-g","daemon off;"]
docker build -t nginx:new1 .
优化二:减少RUN构建
FROM centos:7
ADD nginx-1.15.9.tar.gz /mnt
WORKDIR /mnt/nginx-1.15.9
RUN yum install -y gcc pcre pcre-devel devel zlib-devel make &> /dev/null && \
yum clean all && \
sed -i 's/CFLAGS="$CFLAGS -g"/#CFLAGS="$CFLAGS -g"/g' auto/cc/gcc && \
./configure --prefix=/usr/local/nginx &> /dev/null && \
make &> /dev/null && make install &> /dev/null &&\
rm -rf /mnt/nginx-1.15.9 #使用&&连接减少run的使用
EXPOSE 80
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
docker build -t nginx:new2 .
优化3.多阶段构建
FROM centos:7 as build //相当于别名
ADD nginx-1.15.9.tar.gz /mnt
WORKDIR /mnt/nginx-1.15.9
RUN yum install -y gcc pcre pcre-devel devel zlib-devel make &> /dev/null && \
yum clean all &&\
sed -i 's/CFLAGS="$CFLAGS -g"/#CFLAGS="$CFLAGS -g"/g' auto/cc/gcc && \
./configure --prefix=/usr/local/nginx &> /dev/null && \
make &>/dev/null && \
make install &>/dev/null && \
rm -rf /mnt/nginx-1.15.9
FROM centos:7 #使用FROM命令生成多个镜像,将指定的镜像作为其它镜像的基础镜像环境来构建
EXPOSE 80
VOLUME ["/usr/local/nginx/html"]
COPY --from=build /usr/local/nginx /usr/local/nginx //将文件移动到该镜像
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
docker build -t centos:new3 .
优化四:使用更为轻量级的linux发行版本
debian
alpine
apt add
Sandbox
Busybox
#下载debian压缩包
wget http://download.openvz.org/template/precreated/debian-7.0-x86-minimal.tar.gz
docker import debian-7.0-x86-minimal.tar.gz -- debian:v1
总结
优化四种方式——》基于docker镜像分层的原理来的
- ① 每一条RUN 指令 都会生成一层新的镜像层
- ② 每一层镜像缓存会继承到下一层中 ——》直接影响到镜像的大小
优化方案
-
① 减少RUN 指令的使用
例如:RUN yum -y update
RUN yum install -y gcc gcc-c++
整合为yum install -y gcc gcc-c++ && yum -y update -
② 将执行后的缓存/不用的输出丢入黑洞 (减少缓存)
例如:yum install -y gcc gcc-c++ && yum -y update > /dev/null -
③ 多阶段构建
-
④ 使用更小体积的linux 发行版本