【问题标题】:Minimize size of docker image最小化 docker 镜像的大小
【发布时间】:2020-04-27 18:37:46
【问题描述】:

我正在构建一个用于运行 yarn 作业的 docker 映像。
为了安装纱线,我需要 curl 来获取包存储库。安装 yarn 后,我对 curl 不再感兴趣,所以我再次清除它。
但这对生成的 docker 图像大小没有影响,因为安装 curl 的层仍然是底层图像层(据我了解 docker 图像)。
我对这种特定情况(卷曲和纱线)不太感兴趣,但总的来说如何在这种情况下最小化我的 docker 图像。如何“清除”我的 docker 映像中不再需要的底层?

示例 Dockerfile 供参考:

FROM ubuntu:focal

# Updating and installing curl (not required in final image)
RUN apt update && apt install -y curl

# Using curl to install yarn
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - &&\
        echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
        apt update && apt install -y yarn

# Doing cleanup (no positive effect on image size)
RUN apt purge -y curl && rm -rf /var/lib/apt/lists/* && apt autoremove -y && apt clean -y  

编辑:
只是为了澄清:
ubuntu/focal 本身只有 74 MB 的图像大小。
运行 apt update 后为 95 MB
apt installing curl wget git 之后是 198 MB
即使清除所有这些安装也不会让我回到 74 MB
多阶段构建是一个不错的概念,我将对其进行研究。
尽管这个问题是关于是否可以再次减小单个图像的大小。

【问题讨论】:

  • 我不认为清理会在图像大小方面做很多事情,因为 curl 安装非常小,特别是与基本 Ubuntu 图像相比。如果你真的想要一个小图像,我建议使用 Alpine 作为你的基础图像,它是用来构建小图像的。
  • @camba1 虽然你是对的,但那张 apine 是一个很棒的简约图像,我对如何减小给定图像的大小感兴趣。

标签: docker dockerfile


【解决方案1】:

您可以使用多阶段 Dockerfile 构建映像。

例如:

FROM ubuntu:focal AS building_stage
RUN apt update && apt install -y curl
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - &&\
        echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
        apt update && apt install -y yarn
RUN yarn install # or whatever you want to do with yarn

FROM ubuntu:focal AS running_stage
COPY --from=building_stage /root/node_modules .

构建此 Dockerfile 后,最终映像不包含 yarncurl,但它具有运行最终映像所需的文件。我不知道你想用yarn 做什么,所以我无法从你的示例中展示一个纯粹的例子,但multi stage builds 可能是你想要使用的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2021-04-05
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多