FROM python:3
# Binary dependencies
RUN apt update && apt install -y gfortran libopenblas-dev liblapack-dev
# Wanted Python packages
RUN python3 -m pip install mysqlclient numpy scipy pandas matplotlib

它工作正常,但产生的图像大小为1.75GB(而代码约为50MB)。我怎样才能减少这么大的体积呢?

我也曾尝试使用Alpine Linux,像这样。

FROM python:3-alpine
# Binary dependencies for numpy & scipy; though second one doesn't work anyway
RUN apk add --no-cache --virtual build-dependencies \
    gfortran gcc g++ libstdc++ \
    musl-dev lapack-dev freetype-dev python3-dev
# For mysqlclient
RUN apk --no-cache add mariadb-dev
# Wanted Python packages
RUN python3 -m pip install mysqlclient numpy scipy pandas matplotlib

但Alpine导致了许多不同的奇怪错误。来自上层代码的错误。

File "scipy/odr/setup.py", line 28, in configuration
    blas_info['define_macros'].extend(numpy_nodepr_api['define_macros'])
KeyError: 'define_macros'

那么,怎样才能用提到的软件包获得最小可能的(或至少是较小的)Python 3的图像呢?

python
docker
scipy
dockerfile
alpine-linux
AivanF.
AivanF.
发布于 2020-10-23
1 个回答
jkr
jkr
发布于 2020-10-23
已采纳
0 人赞同

有几件事你可以做,以使你的Docker镜像更小。

  • Use the python:3-slim Docker image as a base. The -slim images do not include packages needed for compiling software.
  • Pin the Python version, let's say to 3.8. Some packages do not have wheel files for python 3.9 yet, so you might have to compile them. It is good practice, in general, to use a more specific tag because the python:3-slim tag will point to different versions of python at different points in time.
  • You can also omit the installation of gfortran, libopenblas-dev, and liblapack-dev. Those packages are necessary for building numpy/scipy, but if you install the wheel files, which are pre-compiled, you do not need to compile any code.
  • Use --no-cache-dir in pip install to disable the cache. If you do not include this, then pip's cache counts toward the Docker image size.
  • There are no linux wheels for mysqlclient, so you will have to compile it. You can install build dependencies, install the package, then remove build dependencies in a single RUN instruction. Keep in mind that libmariadb3 is a runtime dependency of this package.
  • 下面是一个实现上述建议的Docker文件。它使一个Docker镜像达到354MB大。

    FROM python:3.8-slim
    # Install mysqlclient (must be compiled).
    RUN apt-get update -qq \
        && apt-get install --no-install-recommends --yes \
            build-essential \
            default-libmysqlclient-dev \
            # Necessary for mysqlclient runtime. Do not remove.
            libmariadb3 \
        && rm -rf /var/lib/apt/lists/* \
        && python3 -m pip install --no-cache-dir mysqlclient \
        && apt-get autoremove --purge --yes \
            build-essential \
            default-libmysqlclient-dev