Docker v17.05
开始支持多阶段构建 (multistage builds),能有效减少images
的大小,本文以golang
helloword
为例,演示Docker 多阶段构建
。
golang helloword
package main
import "fmt"
func main(){
fmt.Printf("Hello World!");
}
传统构建
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 .
多阶段构建
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
可以发现,采用多阶段构建时,镜像明显较小。