要优化PyTorch的Docker镜像大小,可以采取以下几种方法:
python:3.8-slim
,而不是默认的python:3.9
或python:3.10
。示例多阶段构建Dockerfile:
# 第一阶段:安装依赖项和构建PyTorch环境
FROM pytorch/pytorch:latest AS builder
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
cmake \
git \
libopenblas-dev \
libblas-dev \
liblapack-dev \
libjpeg-dev \
libpng-dev \
libtiff-dev \
libavcodec-dev \
libavformat-dev \
libswscale-dev \
libv4l-dev \
libxvidcore-dev \
libx264-dev \
libjpeg-dev \
libpng-dev \
libpq-dev \
python3-dev \
python3-pip
RUN pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
# 第二阶段:复制必要的文件到最终镜像中
FROM python:3.8-slim
COPY --from=builder /usr/local /usr/local
COPY . /app
WORKDIR /app
RUN pip3 install --no-cache-dir -r requirements.txt
CMD ["python3", "app.py"]
apt-get clean
清理包管理器缓存。rm -rf /var/lib/apt/lists/*
删除APT列表文件。libopenblas
代替openblas
,libjpeg-turbo
代替libjpeg
等。-j$(nproc)
选项运行make
命令。通过以上方法,可以有效地减小PyTorch Docker镜像的大小,从而提高部署效率和性能。