dockefile多阶段构建multi build

多阶段构建 Dockerfile 的几种常见用法

1. 使用数字标记阶段

  • FROM alpineFROM alpine 分别第 0、1 阶段,再通过 COPY --from=0--from=1 将文件集中到最终镜像中。
1
2
3
4
5
6
7
8
9
10
11
# vim Dockerfile
FROM alpine
COPY test1.txt /

FROM alpine
COPY test2.txt /

FROM alpine
COPY --from=0 /test1.txt /tmp
COPY --from=1 /test2.txt /tmp

2. 使用阶段名称(alias)

  • 更易读:FROM alpine AS build1AS build2,然后最后阶段直接 COPY --from=build1--from=build2
FROM alpine as build1
COPY test1.txt /

FROM alpine as build2
COPY test2.txt /

FROM alpine
COPY --from=build1 /test1.txt /test/
COPY --from=build2 /test2.txt /test/

3. 从其他已有镜像拷贝内容

  • 例如 COPY --from=busybox / /test/,直接提取 busybox 镜像中所需资源。
FROM busybox
COPY --from=busybox /  /test/