Advanced multi-stage build patterns

Inheriting from a stage

FROM ubuntu AS base
RUN apt-get update && apt-get install git
FROM base AS src1
RUN git clone …
FROM base as src2
RUN git clone …

Using images directly

FROM alpine
COPY --from=linuxkit/ca-certificates / /

Alias for a common image

FROM alpine:3.6 AS alpineFROM alpine
RUN …
FROM alpine
RUN …
ARG ALPINE_VERSION=3.6FROM alpine:${ALPINE_VERSION} AS alpineFROM alpine
RUN …

Using build arguments in ` --from`

// THIS EXAMPLE IS INTENTIONALLY INVALIDFROM alpine AS build-stage0
RUN …
FROM alpine
ARG src=stage0
COPY --from=build-${src} . .
ARG src=stage0FROM alpine AS build-stage0
RUN …
FROM build-${src} AS copy-srcFROM alpine
COPY --from=copy-src . .

Conditions using build arguments

// THIS EXAMPLE IS INTENTIONALLY INVALIDFROM alpine
RUN …
ARG BUILD_VERSION=1
IF $BUILD_VERSION==1
RUN touch version1
ELSE IF $BUILD_VERSION==2
RUN touch version2
DONE
RUN …
ARG BUILD_VERSION=1FROM alpine AS base
RUN …
FROM base AS branch-version-1
RUN touch version1
FROM base AS branch-version-2
RUN touch version2
FROM branch-version-${BUILD_VERSION} AS after-conditionFROM after-condition
RUN …

Development/test helper for minimal production stage

FROM golang:alpine AS stage0

FROM golang:alpine AS stage1
FROM scratch
COPY --from=stage0 /binary0 /bin
COPY --from=stage1 /binary1 /bin
FROM golang:alpine AS stage0
FROM scratch AS release
COPY --from=stage0 /binary0 /bin
COPY --from=stage1 /binary1 /bin
FROM golang:alpine AS dev-env
COPY --from=release / /
ENTRYPOINT ["ash"]
FROM golang:alpine AS test
COPY --from=release / /
RUN go test …
FROM release

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store