Docker 17.05 或者更高版本支持 multi-stage builds ,即多阶段构建docker镜像。multi-stage builds,最主要的目的是优化镜像,减小镜像体积。
这里以构建go程序为例。
一个简单的go程序
打印hello world, 版本信息和第一个命令行参数
// app.gopackage mainimport ("fmt""os""runtime")func main() {fmt.Println("Hello World,", runtime.Version(), os.Args[1])}
Dockerfile
# build stageFROM golang:alpine AS buildADD . /srcRUN cd /src && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app# final stageFROM scratchWORKDIR /appLABEL name=hiyangCOPY --from=build /src/app /app/ENTRYPOINT ["./app"]
从上面可以看到,透过AS和--from互相沟通,以前需要写两个 Dockerfile,现在只要一个就可以搞定。
golang:alpine 较小的go环境 scratch Dokcer 所提供的最小 Image CGO_ENABLED=0 采用静态编译,编译后的体积变大,但是没有外部依赖,可以在scratch环境运行
构建
$ docker build -t hiyang/go-app .$ docker run --rm hiyang/go-app hiyangHello World, go1.14.6 hiyang
构建后的体积大概是2.07M
