[docker] Multi-stage builds

Posted by clsung on Sunday, May 14, 2017

Consider the following scenario: you are going to rolling update your cluster, and it turns out your network bandwidth is limited for some reason and size of built docker image is not small enough. What’s worse, every instance of cluster will need to pull the docker image before start-up…

Multi-stage builds feature is introduced in Docker Engine 17.05, which can avoid producing two or more Dockfiles. The major benefit is we can have smaller (only required binary) docker image. Here is an simple example to show how to archive it. The source code is on [github][1].

Dockerfile:

FROM golang:1.8-alpine as builder

RUN apk update && apk upgrade && \
	apk add --no-cache git
RUN go get -u sourcegraph.com/sourcegraph/appdash/cmd/...

FROM alpine:3.5  

RUN apk --no-cache add ca-certificates
WORKDIR /
COPY --from=builder /go/bin/appdash .

EXPOSE 7700
EXPOSE 7701

CMD ["/appdash", "serve"]

 

After docker build, we can compare the docker image file size:

REPOSITORY TAG IMAGE ID CREATED SIZE
clsung/appdash                   latest              bf98d0e0f894        17 hours ago        15.5MB
                                       4c6d1097ad0c        17 hours ago        343MB

Ref:

  • [DOCKERCON 2017: MULTI-STAGE BUILDS AND MORE][2]
  • [Use multi-stage builds][3]