使用多阶段构建精简镜像
分离构建层和运行时层,减小镜像体积
使用多阶段构建精简镜像 是 CoddyKit 上的免费 MLOps Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MLOps Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MLOps Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Big Images Hurt
A bloated image is slow to push, pull, and start, and it carries more to patch. Multi-stage builds ship only what you actually need.
The Core Idea
You use one stage to build and a second clean stage to run. Build tools stay behind, so the final image stays small.
Name a Build Stage
Add AS builder to a FROM line to name a stage. You can reference that name later to pull files out of it.
FROM python:3.11 AS builderInstall Into the Builder
In the builder, install dependencies to a known prefix. The --user flag drops everything neatly under one copyable folder.
RUN pip install --user --no-cache-dir -r requirements.txtStart the Runtime Stage
Open a fresh, slim stage for what actually runs. It has none of the compilers or caches the builder needed.
FROM python:3.11-slimCopy Only the Artifacts
Use COPY --from=builder to lift just the installed packages into the runtime stage. The heavy build layer is left behind.
COPY --from=builder /root/.local /root/.localBring in Your Code
Copy your application source into the slim stage too. Now the final image holds your code plus only its runtime dependencies.
COPY . /appFix the Path
User-installed packages live under .local, so add that to PATH. Otherwise the runtime cannot find your installed commands.
ENV PATH=/root/.local/bin:$PATHOnly Last Stage Ships
Docker keeps only the final stage in your image. Everything in earlier stages is discarded unless you explicitly copy it.
Try Distroless
For the smallest, safest result, run on a distroless base with no shell or package manager. Less surface means fewer things to exploit.
Measure the Win
Check the size drop with docker images. Slimming from over a gigabyte to a couple hundred megabytes is common and worth it.
docker images model-apiQuick Check
Let us check what a multi-stage build keeps.
Recap
You split build from runtime, copied just the artifacts with COPY --from, fixed PATH, and shrank the image. Lean and fast. ✅
常见问题解答
「使用多阶段构建精简镜像」课时是免费的吗?
是的 — 「使用多阶段构建精简镜像」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MLOps Academy 课程的其余内容,请升级到 CoddyKit PRO。 MLOps Academy 课程共包含 4 节课。
「使用多阶段构建精简镜像」这节课中我会学到什么?
分离构建层和运行时层,减小镜像体积 你通过在浏览器中直接运行的动手代码来练习 MLOps Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MLOps Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MLOps Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用多阶段构建精简镜像」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MLOps Academy 课中编写并运行代码吗?
能。每节 MLOps Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 为模型 API 编写 Dockerfile
- 使用多阶段构建精简镜像
- 通过环境变量传递配置
- 在本地运行并测试容器