python - Flask 应用程序的 Docker 多阶段构建

标签 python docker docker-multi-stage-build

我想对具有大量依赖项的 flask 应用程序进行 dockerize。我的目标是减小最终 Docker 镜像的大小。

我尝试了多阶段构建,但它并没有减少最终 Docker 镜像的大小。

下面是我的Dockerfile

FROM python:3.6-slim-buster as base

RUN apt-get update && apt-get install --no-install-recommends --no-upgrade -y \
    libglib2.0-0 libxext6 libsm6 libxrender1 libfontconfig1 && rm -rf /var/lib/apt/lists/*


WORKDIR /wheels

COPY requirements.txt /wheels

RUN pip install -U pip \
   && pip wheel -r requirements.txt



FROM python:3.6-slim-buster

COPY --from=base /wheels /wheels


RUN pip install -U pip \
       && pip install -r /wheels/requirements.txt \
                      -f /wheels \
       && rm -rf /wheels \
       && rm -rf /root/.cache/pip/* 

...

最后一个pip install...命令占用了905MB

我应该如何将所有需求从最终镜像中分离出来并减少最终 docker 镜像的整体大小?

最佳答案

在最终的RUN中删除/wheels不会使您的镜像变小——这些文件仍然位于最终镜像所构建的上一层中。一旦您复制了某些内容,它就会出现在您的图像中。

我建议将代码安装到构建镜像中的 virtualenv 中(尽管您也可以执行 --user install)并将 virtualenv 复制到运行时镜像中。

FROM python:3.7-slim AS compile-image
RUN apt-get update
RUN apt-get install -y --no-install-recommends build-essential gcc

RUN python -m venv /opt/venv
# Make sure we use the virtualenv:
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY setup.py .
COPY myapp/ .
RUN pip install .

FROM python:3.7-slim AS build-image
COPY --from=compile-image /opt/venv /opt/venv

# Make sure we use the virtualenv:
ENV PATH="/opt/venv/bin:$PATH"
CMD ['myapp']

请参阅此处的原始版本和更多说明:https://pythonspeed.com/articles/multi-stage-docker-python/

关于python - Flask 应用程序的 Docker 多阶段构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57226224/

相关文章:

python - 使用 SQLAlchemy 思考特征

docker - 无法从Docker容器打开URL

java - 创建容器时附加 docker_

docker - 无缓存的多阶段Docker构建

Quarkus native 可执行文件构建 : high memory consumption

python - 如何从python API azure sdk获取azure规模集实例的公共(public)IP?

python - Twitter.com 请求错误

python - 除了 GET、PUT、POST、DELETE 之外的 Flask-RESTful 自定义路由

windows - 如何修复 Windows 中的 "VirtualBox Interface has active connections"错误?

Docker 多阶段构建在上一阶段的副本上失败