diff --git a/content/build/bake/contexts.md b/content/build/bake/contexts.md index 8b2744cd289d..fa562f8160f7 100644 --- a/content/build/bake/contexts.md +++ b/content/build/bake/contexts.md @@ -88,3 +88,49 @@ target "app" { In most cases you should just use a single multi-stage Dockerfile with multiple targets for similar behavior. This case is only recommended when you have multiple Dockerfiles that can't be easily merged into one. + +## Deduplicate context transfer + +When building multiple targets using the same context, transferring the context +for each target can be inefficient. To avoid transferring the same context +multiple times, use a named context and reference it for each target. + +```dockerfile +FROM alpine AS base +WORKDIR /work + +FROM scratch AS ctx +COPY --link . . + +FROM base AS target1 +RUN apk add git +RUN --mount=from=ctx ls -l + +FROM base AS target2 +RUN apk add curl +RUN --mount=from=ctx ls -l +``` + +```hcl +group "default" { + targets = ["target1", "target2"] +} + +target "ctx" { + target = "ctx" +} + +target "target1" { + target = "target1" + contexts = { + ctx = "target:ctx" + } +} + +target "target2" { + target = "target2" + contexts = { + ctx = "target:ctx" + } +} +```