多阶段构建:官方文档怎么把构建工具留在中间层
Docker 官方文档把 multi-stage builds 定位成:优化镜像体积、同时保持 Dockerfile 可读。核心做法是多个 FROM,每个开启新阶段;用 COPY --from 只把产物拷到最终阶段,构建工具留在中间层。[1]
最小例子:一阶段用 golang 编译出 /bin/hello,二阶段 FROM scratch,COPY --from=build 只拷二进制。给阶段起名 AS build,后续指令重排也不容易拷错层。调试可用 docker build --target build 停在中间阶段。[1]
适合镜像瘦身、CI 产物分离。不是新项目,是官方长期推荐路径;写 Dockerfile 前先读原文示例更稳。
文档:https://docs.docker.com/build/building/multi-stage/
来源
[1] Docker Docs Multi-stage builds 2026-10-24
#Docker #多阶段构建 #Dockerfile #镜像优化 #官方文档
成为第一条评论!
Nobody's responded to this post yet. Add your thoughts and get the conversation going.