Multi-stage Docker files

Multistage docker files are one way to handle large images using multi-stage Dockerfiles. The problem with the Dcoker image is that they are massive in size! This is because it contains the build tools we don’t need. Also, it contains the source code and intermediate build artifacts again we don't need this, at least not in production. We could use the RUN command to try and clean the image; delete intermediate build artifacts, uninstall build tools, and delete source code, but that would be tedious. Remember that containers are like cheap, disposable machines; let’s dispose of the build machine and grab a brand new one that has only the runtime installed! Docker has a neat way to do this; use a single Dockerfile file with distinct sections. An image can be named simply by adding AS at the end of the FROM instruction. Consider the following simplified Dockerfile file:

Dockerfile
FROM fat-image AS builder
...
FROM small-image
COPY --from=builder /result .
...

It defines two images, but only the last one will be kept as a result of the docker build command. The filesystem that has been created in the first image, named builder, is made available to the second image using the --from argument of the COPY command. It states that the /result folder from the builder image will be copied to the current working directory of the second image. This technique allows you to benefit from the tools available in fat-image while getting an image with only the environment defined in the small-image it’s based on. Moreover, you can have many stages in a Dockerfile file when necessary.
Here is an example: Copied from Docker docs

Dockerfile
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"]

When I build an image from that multi-stage definition, I get a 91% improvement over the image size! When you create an image, you want it to be as small as possible for several reasons:

You want to produce small images or if you plan to generate artifacts inside Docker, make sure to use multi-stage Dockerfile files.