Dockerfile四大优化

x33g5p2x  于2021-12-01 转载在 Docker  
字(2.8k)|赞(0)|评价(0)|浏览(362)

一、未优化前

mkdir nginx 
mkdir -p nginx/nginx_v1 nginx/nginx_v2 nginx/nginx_v3 
rz -E

FROM 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
#关闭debug日志
RUN sed -i 's/CFLAGS="$CFLAGS -g"/#CFLAGS="$CFLAGS -g"/g' auto/cc/gcc 
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;"]
docker build -t "nginx:v1" .
#查看镜像大小 docker images

docker run -d -P nginx:v1
PS 1 : 不要用docker run -d -P nginx:v1 /bin/bash 
/bin/bash 指定了shell环境,而我们的dockerfile 已指定CMD,即默认启动时加载的命令/执行程序,使用/bin/bash这种
shell环境会覆盖cmd命令,导致容器运行时nginx 不会加载

PS 2: VOLUME 宿主机的挂载点可使用docker insepct 查看
① 默认会放在var/lib/docker/volumes/容器ID/_data中
② 可以使用docker run -d -P -v /data1:/usr/local/nginx/html 来指定

二、优化1:不需要输出的指令丢入/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.15.9.tar.gz /mnt
WORKDIR /mnt/nginx-1.15.9
#关闭debug日志
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.15.9
EXPOSE 80
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx""-g","daemon off;"]

docker build -t nginx:v1 .

三、优化2:减少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 
EXPOSE 80
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]

docker build -f Dockerfile -t nginx:v3 .

四、优化3:多阶段构建(使用FROM命令生成多个镜像,将指定的镜像做为其他镜像的基础镜像环境来构建)

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 
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;"]

五、优化4 :使用更为轻量级的linux 发行版本

debian
alpine
apt add

[外链图片转存中...(img-Pjo8YquO-1638289256662)]

# 五、优化4 :使用更为轻量级的linux 发行版本

debian
alpine
apt add

相关文章