如何使用多阶段构建减小 python (docker) 图像大小? [英] How do I reduce a python (docker) image size using a multi-stage build?

查看:52
本文介绍了如何使用多阶段构建减小 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) 图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆