Allows to build multiple images in one Dockerfile and pass data between them to optimize the final build.

Useful to optimize image sizes without compromising readability as much.

FROM golang:1.16 AS builder
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 go build -a -installsuffix cgo -o app .
 
FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app ./
CMD ["./app"]  

Build can be stopped at the specific target:

FROM ubuntu AS base
RUN echo "base"
 
FROM base AS stage1
RUN echo "stage1"
 
FROM base AS stage2
RUN echo "stage2"
docker build --no-cache -f Dockerfile --target stage2 .

Starting from v23.0 BuildKit is enabled by default, and the stage1 in the example above will be skipped.

See also