为减少镜像重量下的多阶段构建镜像--关键词 - COPY --from=

如何理解多阶段构建?

Multi-stage builds give the benefits of the builder pattern without the hassle of maintaining three separate files: 多阶段构建的为构建模式提供了很多益处,避免分多个文件维护的麻烦,如:
FROM golang:1.7.3

WORKDIR /go/src/github.com/alexellis/href-counter/

RUN go get -d -v golang.org/x/net/html
COPY app.go    .

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=0 /go/src/github.com/alexellis/href-counter/app    .

CMD ["./app"]

 

This is huge for developers and maintainers, especially when you support multiple Dockerfiles for different architectures such as the Raspberry Pi.

对于开发人员和维护人员而言,为树莓派等不同的架构支持多个Dockerfile时,这是很令人纠结的。

 

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>

不论哪个FROM是最后基础镜像的声明,通常会涉及额外次数去使用FROM
去中间层的镜像复制内容,可以使用 COPY --from=<base_image_number>

The second PR mentioned improves on this syntax and when merged would mean you can do something more like:

第二个公共版本中,提到改进了这种语法,也就是“合并”后意味着您可以做更多的事情,如:

 

FROM golang:1.7.3 as builder

WORKDIR /go/src/github.com/alexellis/href-counter/

RUN go get -d -v golang.org/x/net/html
COPY app.go    .

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .

CMD ["./app"]

 

注:
    1、FROM golang:1.7.3 as builder 给镜像取个别名 builder
    2、WORKDIR 当前工作目录 /go/src/github.com/alexellis/href-counter/app
    3、RUN 构建镜像时运行命令
    4、COPY 将脚本app.go拷贝到当前工作目录
    5、FROM alpine:latest 基于 alpine 一个小巧的 linux  
    6、RUN apk --no-cache add ca-certificates 
    7、FROM alpine:latest 基于 alpine 一个小巧的 linux  
    8、WORKDIR /root/ 切换至root目录 
    9、COPY --from=builder /go/src/github.com/alexellis/href-counter/app . 将上一层镜像复制制定目录复制到当前工作目录
    10、实例时运行 ./app

 

那么我门们该如何做呐?

上一篇:docker制作alpine初始镜像


下一篇:[Mise] Focus in input field on page load with `x-init` in Alpine JS