镜像的优化
- 选择最精简的基础镜像
- 减少镜像的层数
- 清理镜像构建的中间产物
- 注意优化网络请求
- 尽量去用构建缓存
- 使用多阶段构建镜像
源码安装nginx
试着在容器中源码安装nginx,看看过程中会有什么问题
docker run -it --rm rhel7 bash
首先在容器中配置yum源
cd /etc/yum.repos.d/
vi dvd.repo
[dvd]
name=rhel7.6
gpgcheck=0
baseurl=http://172.25.254.36/rhel7.6
yum install vim gcc make pcre-devel zlib-devel
这一步后面会有报错,解决
rpmdb --rebuilddb
再次安装
docker cp nginx-1.16.1.tar.gz ed0ddb302d30:/root/
解压:
tar zxf nginx-1.16.1.tar.gz
cd nginx-1.16.1.tar.gz
cd auto
cd cc
vim gcc
# debug
# CFLAGS="$CFLAGS -g" # 注释debug,使编译环境纯净
编译
./configure --prefix=/usr/local/nginx/‘
安装
make && make install
cd /usr/local/nginx/
ls
使用Dockerfile编译安装nginx
首先写好yum源,方便后面导入容器
vim dvd.repo
[dvd]
name=rhel7.6
gpgcheck=0
baseurl=http://172.25.254.36/rhel7.6
编辑Dockerfile,把要做的过程都写进去
vim Dockerfile
FROM rhel7
COPY dvd.repo /etc/yum.repos.d/
ADD nginx-1.16.1.tar.gz /mnt
RUN rpmdb --rebuilddb
RUN yum install -y gcc vim make pcre-devel zlib-devel
WORKDIR /mnt/nginx-1.16.1/auto/cc
RUN sed -i.bak 's/CFLAGS="$CFLAGS -g"/# CFLAGS="$CFLAGS -g"/g' gcc
WORKDIR /mnt/nginx-1.16.1
RUN ./configure --prefix=/usr/local/nginx
RUN make
RUN make install
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
构建镜像
docker build -t nginx:v1 .
docker history nginx:v1 #这里我们可以查看到构建过程
运行
docker run -d --name web nginx:v1 #给nginx:v1镜像取名为web,-d在后台运行
测试
docker inspect web #查看到分配的IP地址为172.17.0.2
curl 172.17.0.2 #可以看到nginx默认发布页面
镜像的优化
减少镜像层数
vim Dockerfile
FROM rhel7
COPY dvd.repo /etc/yum.repos.d/
ADD nginx-1.16.1.tar.gz /mnt
WORKDIR /mnt/nginx-1.16.1
RUN rpmdb --rebuilddb && yum install -y gcc vim make pcre-devel zlib-devel && sed -i.bak 's/CFLAGS="$CFLAGS -g"/# CFLAGS="$CFLAGS -g"/g' auto/cc/gcc && ./configure --prefix=/usr/local/nginx && make && make install
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
docker build -t nginx:v2 .
docker images #查看重构后的镜像大小,v2比v1减少了7M
清理镜像构建的中间产物
vim Dockerfile
FROM rhel7
COPY dvd.repo /etc/yum.repos.d/
ADD nginx-1.16.1.tar.gz /mnt
WORKDIR /mnt/nginx-1.16.1
RUN rpmdb --rebuilddb && yum install -y gcc vim make pcre-devel zlib-devel && sed -i.bak 's/CFLAGS="$CFLAGS -g"/# CFLAGS="$CFLAGS -g"/g' auto/cc/gcc && ./configure --prefix=/usr/local/nginx && make && make install && yum clean all && rm -fr /mnt/nginx-1.16.1
VOLUME ["/usr/local/nginx/html"]
CMD ["/usr/local/nginx/sbin/nginx","-g","daemon off;"]
使用多阶段构建镜像