多阶段构建优点
1. 只生成最后一阶段镜像,不生成中间镜像
2. 后阶段可以使用前阶段生成的文件,从而构建最小化镜像
3. 构建可以镜像时,可以指定构建特定阶段,不执行全部构建内容。日常使用第一阶段构建程序或运行程序,稳定时执行全部,构建出需要的镜像。
后阶段可以使用前阶段生成的文件:使用方法
第一阶段中《FROM golang:1.21 as build》 别名设定为 build
第二阶段中《COPY --from=build /bin/hello /bin/hello》使用--from=build 时,会调用第一阶段生成文件进行引用。不使用则引用不到。
准备测试文件
建立测试文件
#建立测试文件
cat > ./main.go <<EOF
package main
import "fmt"
func main() {
fmt.Println("hello, world")
}
EOF
建立Dockerfile文件
# syntax=docker/dockerfile:1
FROM golang:1.21 as build
WORKDIR /src
COPY ./main.go ./
RUN go build -o /bin/hello ./main.go
FROM scratch
COPY --from=build /bin/hello /bin/hello
CMD ["/bin/hello"]
使用命名多阶段构建
运行命令
docker build -t hello .
执行结果如下
user@tesla-t4:~/docker-multi$ docker build -t hello .
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 3.072kB
Step 1/7 : FROM golang:1.21 as build
---> 9c541743933a
Step 2/7 : WORKDIR /src
---> Using cache
---> 9dcfcbaf87ab
Step 3/7 : COPY ./main.go ./
---> 0203b496f714
Step 4/7 : RUN go build -o /bin/hello ./main.go
---> Running in 4b312410cc7d
Removing intermediate container 4b312410cc7d
---> e6bedc995657
Step 5/7 : FROM scratch
--->
Step 6/7 : COPY --from=build /bin/hello /bin/hello
---> a74952fc7368
Step 7/7 : CMD ["/bin/hello"]
---> Running in 653537b32292
Removing intermediate container 653537b32292
---> 605a275a494c
Successfully built 605a275a494c
Successfully tagged hello:latest
在特定的生成阶段停止
运行命令
docker build --target build -t hello .
执行结果如下
user@tesla-t4:~/docker-multi$ docker build --target build -t hello .
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 3.072kB
Step 1/4 : FROM golang:1.21 as build
---> 9c541743933a
Step 2/4 : WORKDIR /src
---> Using cache
---> 9dcfcbaf87ab
Step 3/4 : COPY ./main.go ./
---> Using cache
---> 0203b496f714
Step 4/4 : RUN go build -o /bin/hello ./main.go
---> Using cache
---> e6bedc995657
Successfully built e6bedc995657
Successfully tagged hello:latest
使用外部图像作为构建
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf