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

查看:596
本文介绍了如何使用多阶段构建减小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 first image to the second, without the compilers themselves (gcc, postgers-dev, python-dev etc..)

The最终目的是拥有一个较小的图像,运行python和我需要的python包。

The final objcetive 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-和docker-multistage-build

这篇关于如何使用多阶段构建减小python(docker)图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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