How do I reduce a python (docker) image size using a multi-stage build?(如何使用多阶段构建减小 python (docker) 图像大小?)
问题描述
我正在寻找一种使用 python 和 Dockerfile 创建多阶段构建的方法:
I am looking for a way to create multistage builds with python and Dockerfile:
例如,使用以下图片:
第一张图片:安装所有编译时要求,并安装所有需要的 python 模块
1st image: install all compile-time requirements, and install all needed python modules
第二个映像:将所有已编译/构建的包从第一个映像复制到第二个映像,不包括编译器本身(gcc、postgers-dev、python-dev 等)
2nd image: copy all compiled/built packages from the first image to the second, without the compilers themselves (gcc, postgers-dev, python-dev, etc..)
最终目标是拥有一个更小的镜像,运行 python 和我需要的 python 包.
The final objective is to have a smaller image, running python and the python packages that I need.
简而言之:我如何包装"在第一个图像中创建的所有已编译模块(站点包/外部库),并将它们复制到干净"中方式,到第二张图片.
In short: how can I 'wrap' all the compiled modules (site-packages / external libs) that were created in the first image, and copy them in a 'clean' manner, to the 2nd image.
推荐答案
好的,所以我的解决方案是使用wheel,它允许我们在第一个映像上编译,为所有依赖项创建wheel文件并将它们安装在第二个映像中,而无需安装编译器
ok so my solution is using wheel, it lets us compile on first image, create wheel files for all dependencies and install them in the second image, without installing the compilers
FROM python:2.7-alpine as base
RUN mkdir /svc
COPY . /svc
WORKDIR /svc
RUN apk add --update
postgresql-dev
gcc
musl-dev
linux-headers
RUN pip install wheel && pip wheel . --wheel-dir=/svc/wheels
FROM python:2.7-alpine
COPY --from=base /svc /svc
WORKDIR /svc
RUN pip install --no-index --find-links=/svc/wheels -r requirements.txt
您可以在以下博客文章中看到我对此的回答
You can see my answer regarding this in the following blog post
https://www.blogfoobar.com/post/2018/02/10/python-and-docker-multistage-build
这篇关于如何使用多阶段构建减小 python (docker) 图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用多阶段构建减小 python (docker) 图像大小?


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01