为什么多级docker映像比单级更大?

2024-10-02 20:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个microservice(https://github.com/staticdev/enelvo-microservice),它需要克隆一个git存储库来创建一个docker映像,带有一个单阶段docker文件最终映像有759MB:

FROM python:3.7.6-slim-stretch

# set the working directory to /app
WORKDIR /app

# copy the current directory contents into the container at /app
COPY . /app

RUN apt-get update && apt-get install -y git \
 && pip install -r requirements.txt \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src \
 && cd enelvo-src \
 && python setup.py install \
 && cd .. \
 && mv enelvo-src/enelvo enelvo \
 && rm -fr enelvo-src

EXPOSE 50051

# run app.py when the container launches
CMD ["python", "app.py"]

我已经尝试过使用多级构建(https://blog.bitsrc.io/a-guide-to-docker-multi-stage-builds-206e8f31aeb8)的方法,在没有git和apt get列表(来自更新)的情况下减小图像大小:

FROM python:3.7.6-slim-stretch as cloner

RUN apt-get update && apt-get install -y git \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src

FROM python:3.7.6-slim-stretch

COPY --from=cloner /enelvo-src /app/enelvo-src

# set the working directory to /app
WORKDIR /app

# copy the current directory contents into the container at /app
COPY . /app

RUN pip install -r requirements.txt \
 && cd enelvo-src \
 && python setup.py install \
 && cd .. \
 && mv enelvo-src/enelvo enelvo \
 && rm -fr enelvo-src

EXPOSE 50051

# run app.py when the container launches
CMD ["python", "app.py"]

问题是,在这样做之后,最终的大小变得更大(815MB)。你知道在这种情况下会出什么问题吗


Tags: installthepyhttpsgitsrcgithubcom
1条回答
网友
1楼 · 发布于 2024-10-02 20:37:54

在你的第一个例子中,你正在跑步

RUN git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src \
    ... \
 && rm -fr enelvo-src

因此enelvo-src树永远不存在于这个特定的RUN指令之外;在Docker可以用它构建一个层之前,它就被删除了

在第二个示例中,您正在运行

COPY  from=cloner /enelvo-src /app/enelvo-src
RUN rm -fr enelvo-src

Docker在第一步之后内部创建一个包含源树内容的图像层。随后的RUN rm实际上并没有使图像变小,它只是记录了从技术上讲,先前层中存在的内容不再是文件系统的一部分

通常,使用多阶段构建的标准方法是在早期阶段尽可能多地构建,并且只将最终结果COPY添加到运行时映像中。对于Python包,一种可以很好地工作的方法是从包中构建一个wheel

FROM python:3.7.6-slim-stretch as build
WORKDIR /build
RUN apt-get update && apt-get install -y git \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src
 && ...
 && python setup.py bdist_wheel  # (not "install")

FROM python:3.7.6-slim-stretch
WORKDIR /app
COPY  from=build /build/dist/wheel/enelvo*.whl .
RUN pip install enelvo*.whl
...

相关问题 更多 >