Docker images 多阶段构建

发布时间: 更新时间: 总字数:211 阅读时间:1m 作者: IP上海 分享 网址

Docker v17.05开始支持多阶段构建 (multistage builds),能有效减少images的大小,本文以golang helloword 为例,演示Docker 多阶段构建

golang helloword

  • helloworld.go
package main

import "fmt"

func main(){
    fmt.Printf("Hello World!");
}

传统构建

  • Dockerfile.one
FROM golang:1.11.10-alpine

WORKDIR /go/src/github.com/xiexianbin/go-helloworld/
ADD helloworld.go .
RUN GOOS=linux go build helloworld.go \
  && cp helloworld /root
WORKDIR /root/

CMD ["./app"]
  • 构建命令
dockerfile docker build -t xiexianbin/go-helloworld:1 -f Dockerfile.one .

多阶段构建

  • Dockerfile.one
FROM golang:1.11.10-alpine as builder

WORKDIR /go/src/github.com/xiexianbin/go-helloworld/
ADD helloworld.go .
RUN GOOS=linux go build helloworld.go

FROM alpine:latest as prod

WORKDIR /root/
COPY --from=0 /go/src/github.com/xiexianbin/go-helloworld/helloworld .
CMD ["./app"]
  • 构建命令
dockerfile docker build -t xiexianbin/go-helloworld:2 -f Dockerfile .

构建后镜像对比

➜  dockerfile docker images | grep helloworld
xiexianbin/go-helloworld   1                9fe54345596b   3 seconds ago        315MB
xiexianbin/go-helloworld   2                777d49ca77c6   About a minute ago   7.53MB

可以发现,采用多阶段构建时,镜像明显较小。

Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数