docker服务镜像瘦身方法
为什么要瘦身
- 空间:镜像占满硬盘
- 时间:拉取镜像缓慢
修改前后的dockerfile
先上修改后的dockerfile
FROM python:3.8-slim
COPY /.build/ /app/
# 安装python库
RUN echo "==> Install curl and helper tools..." && \
apt-get update && \
apt-get install -y python3-pip curl && \
pip3 install --no-cache-dir -r /app/requirements.txt -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com && \
echo "==> Clean up..." && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* && \
cd /root && tar zxvf nltk_data.tar.gz && rm nltk_data.tar.gz && \
apt-get remove --auto-remove -y python3-pip
# 复制脚本
COPY /deploy/ /app/deploy/
COPY /src/ /app/src/
# 编译py脚本至pyc,并删除py脚本
RUN python3 -m compileall -b /app/ && \
find /app/ -name '*.py' -delete
# 环境变量
ENV TZ Asia/Shanghai
ENV HEALTHCHECK_PORT 12371
# 健康检查
HEALTHCHECK --interval=60s --timeout=10s --retries=3 --start-period=10s \
CMD sh /app/deploy/healthcheck.sh
# 运行
CMD ["python3", "app/deploy/main.pyc"]
再上修改前的dockerfile
FROM python:3.8
COPY /.build/ /app/
# Install any needed packages specified in requirements.txt
RUN pip install --upgrade pip -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com
RUN pip install -r app/requirements.txt -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com
# Copy the current directory contents into the container at /app
COPY /deploy/ /app/deploy/
COPY /src/ /app/src/
# download nltk model
RUN pip install nltk==3.5
RUN cd /root && tar zxvf nltk_data.tar.gz
# Define environment variable
ENV TZ Asia/Shanghai
# Run app.py when the container launche
CMD ["python", "app/deploy/main.py"]
镜像打包下来,一个是369MB,一个是1.16GB,差了3倍。
压缩研究过程
- 镜像base的选择
- pip不必要的安装
- docker系统不必要的安装
- 不必要依赖的卸载
- docker layer 优化
- 残留文件的删除
- .dockerignore
镜像base的选择
资源
常见base
- python
- centos
- aliphe
- debian
- ubuntu