Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 111 ยท Dockerfiles

docker buildx bake

Describe many Docker image builds in one docker-bake.hcl file: targets, groups, variables, inheritance, matrix builds, overrides, Compose files and CI use.

A single docker build command is easy to remember. A project that builds three images, for two platforms, with different tags for CI and for releases, is not: the command grows to a dozen flags that live in a wiki page or a shell script. docker buildx bake solves this by moving the build options into a file. The file describes what to build (targets, contexts, arguments, tags, platforms), and bake builds all of it, in parallel, with one command.

This lesson teaches the HCL format of docker-bake.hcl, how targets inherit from each other, how to use variables and command-line overrides, and how bake fits into CI. Everything was run on Docker Engine 29.8 with buildx 0.37; the BuildKit lesson introduces the engine behind it.

A first bake file

Imagine a folder with two small services, each with its own Dockerfile:

TEXT
project/
โ”œโ”€โ”€ docker-bake.hcl
โ”œโ”€โ”€ api/Dockerfile
โ””โ”€โ”€ web/Dockerfile

Both Dockerfiles take an argument and bake it into the image:

DOCKERFILE
FROM alpine:3.22
ARG GREETING=hello
RUN echo "api says $GREETING" > /msg
CMD ["cat", "/msg"]

The web Dockerfile is identical except for the word web. Now the bake file:

HCL
variable "TAG" {
  default = "dev"
}

group "default" {
  targets = ["api", "web"]
}

target "base" {
  args = { GREETING = "hi there" }
}

target "api" {
  inherits = ["base"]
  context  = "./api"
  tags     = ["bk-api:${TAG}"]
}

target "web" {
  inherits  = ["base"]
  context   = "./web"
  tags      = ["bk-web:${TAG}"]
  platforms = ["linux/amd64", "linux/arm64"]
}

Four building blocks appear here:

  • A target is one build. Its fields mirror the options of docker buildx build: context, dockerfile, args, tags, platforms, target, output, cache-from, cache-to, labels and more.
  • A group is a named list of targets. A group called default is what bake builds when you name nothing.
  • A variable has an optional default and can be read in any string with ${NAME}. Environment variables of the same name override the default.
  • inherits copies the fields of other targets, so shared settings are written once.

When you run docker buildx bake without a file name, it looks for docker-bake.hcl, docker-bake.json, docker-compose.yml or compose.yaml (and a few related names) in the current folder.

flowchart TD
    G["group default"] --> A["target api"]
    G --> W["target web"]
    B["target base<br/>args GREETING"] -. inherits .-> A
    B -. inherits .-> W
    A --> IA["image bk-api:dev"]
    W --> IW["image bk-web:dev<br/>amd64 + arm64"]

Running bake with no arguments builds the default group; both targets reuse the settings from base.

See the plan first with --print

Before building anything, ask bake what it would do. --print evaluates variables and inheritance and prints the result as JSON, without running any build:

CONSOLE
$ docker buildx bake --print
{
  "group": {
    "default": {
      "targets": [
        "api",
        "web"
      ]
    }
  },
  "target": {
    "api": {
      "context": "api",
      "dockerfile": "Dockerfile",
      "args": {
        "GREETING": "hi there"
      },
      "tags": [
        "bk-api:dev"
      ]
    },
    "web": {
      "context": "web",
      "dockerfile": "Dockerfile",
      "args": {
        "GREETING": "hi there"
      },
      "tags": [
        "bk-web:dev"
      ],
      "platforms": [
        "linux/amd64",
        "linux/arm64"
      ]
    }
  }
}

Both targets received GREETING from base, and ${TAG} became dev. --print is the best debugging tool for bake files, and it is a great check in CI: the output is the exact set of builds that will run. Two more listing commands help you explore an unfamiliar project:

CONSOLE
$ docker buildx bake --list targets
TARGET	DESCRIPTION
api	
base	
default	api, web
web	
$ docker buildx bake --list variables
VARIABLE	TYPE	VALUE	DESCRIPTION
TAG			dev

You can add a description field to targets and variables, and it shows up in these tables. That makes a bake file self-documenting.

Building

Build everything in the default group. Because the images are only needed on this machine, add --load to put the results into the local image store (the web target has two platforms, so this needs the containerd image store, the default in Docker 29; see Multi-Platform Images):

CONSOLE
$ docker buildx bake --load
...
#13 [api] exporting to image
#13 naming to docker.io/library/bk-api:dev 0.3s done
...
#14 [web] exporting to image
#14 naming to docker.io/library/bk-web:dev 0.3s done
$ docker run --rm bk-api:dev
api says hi there
$ docker run --rm bk-web:dev
web says hi there

Bake started both builds at the same time and merged their progress into one display. When targets share a stage or a base image, BuildKit builds it only once. Compare that with two separate docker build commands run one after the other.

Build just one target by naming it, and override a variable from the environment:

CONSOLE
$ TAG=v2 docker buildx bake api --load
$ docker image ls bk-api --format '{{.Repository}}:{{.Tag}}'
bk-api:v2
bk-api:dev

Now there are two tags for the api image: the earlier dev and the new v2.

Overriding from the command line

--set changes any target field without editing the file. The pattern is target.field=value, and * matches every target:

CONSOLE
$ docker buildx bake --set '*.args.GREETING=cli' web --load
$ docker run --rm bk-web:dev
web says cli

The same image name bk-web:dev now contains a different greeting, because the build argument changed. Other useful overrides:

CONSOLE
$ docker buildx bake --set '*.platform=linux/amd64' --load    # build one platform only
$ docker buildx bake --set 'web.output=type=registry' web     # same as --push for one target
$ docker buildx bake --no-cache                               # ignore the build cache
$ docker buildx bake --pull                                   # re-check base images

--push and --load are shorthand for setting output on every target. --sbom and --provenance switch on attestations everywhere; see Docker Scout, SBOMs and Provenance.

Checking the Dockerfiles

bake can run the Dockerfile linter from BuildKit on every target:

CONSOLE
$ docker buildx bake --check
Check complete, no warnings found.

This evaluates the same checks as docker build --check (unused arguments, casing of instructions, undefined variables and so on), so it makes a cheap CI gate. See Dockerfile Best Practices for what the rules look for.

Variables, functions and matrices

HCL is more than a data format. Variables can have types and validation, and you can compute values:

HCL
variable "REGISTRY" {
  default = "registry.example.com/team"
}

variable "VERSION" {
  default = "0.0.0"
}

function "tag" {
  params = [name]
  result = ["${REGISTRY}/${name}:${VERSION}", "${REGISTRY}/${name}:latest"]
}

target "api" {
  context = "./api"
  tags    = tag("api")
}

Running VERSION=1.4.2 docker buildx bake --print api would show the two tags registry.example.com/team/api:1.4.2 and registry.example.com/team/api:latest. A function keeps the tagging policy in one place, which pairs well with Image Tagging Strategy.

A matrix creates a target for every combination of values, which is how you test one app against several runtime versions:

HCL
target "app" {
  name   = "app-${replace(py, ".", "-")}"
  matrix = {
    py = ["3.12", "3.13"]
  }
  args = { PYTHON_VERSION = py }
  tags = ["myapp:py${py}"]
}

This defines two targets named app-3-12 and app-3-13. Target names must be valid identifiers, which is why the dot in the version is replaced. Matrix entries can also be objects with several fields when you need more than one dimension.

Using bake with Compose files

If the folder has a Compose file, bake can build the build: sections of its services directly:

CONSOLE
$ docker buildx bake -f compose.yaml

Each service with a build section becomes a target. You can combine files, for example a Compose file for the base definition and a bake file that adds platforms and cache settings:

CONSOLE
$ docker buildx bake -f compose.yaml -f docker-bake.override.hcl

Later files override earlier ones. Compose's own docker compose build also uses bake under the hood by default, so the two tools agree about how a service gets built (Compose Commands).

Bake in CI

In a pipeline, a bake file replaces a pile of YAML steps. Typical settings go into a dedicated target and the pipeline only chooses variables:

HCL
target "release" {
  inherits   = ["api"]
  platforms  = ["linux/amd64", "linux/arm64"]
  cache-from = ["type=registry,ref=registry.example.com/team/api:cache"]
  cache-to   = ["type=registry,ref=registry.example.com/team/api:cache,mode=max"]
  attest = [
    "type=provenance,mode=max",
    "type=sbom"
  ]
}
CONSOLE
$ VERSION=$GIT_TAG docker buildx bake release --push

The same file works on a laptop (bake api --load) and in CI (bake release --push), so builds stay identical in both places. Read CI Pipelines and Build Optimization for the cache settings in context. Some CI systems provide a ready-made bake action that also supports remote definitions: docker buildx bake https://github.com/org/repo.git#main builds a file straight from a Git repository.

A bake file is code that decides what runs on your build machine. Remote bake definitions and --allow flags (which grant a build access to the local file system or to the network) should only be used with sources you trust. Read the file, or run --print, before you build something you did not write.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does docker buildx bake --print do?

    --print resolves variables and inheritance and shows exactly what would be built, so you can check the plan before running it.
  2. 2. You run docker buildx bake with no target name. What gets built?

    Without arguments bake builds the default group, so name a group default to define what 'build everything' means.
  3. 3. How do you change one build argument for every target without editing the file?

    --set uses the pattern target.field=value, and * matches all targets.
  4. 4. Why is a matrix useful?

    A matrix expands one target definition into many named targets, which keeps version-testing builds short.

Summary

  • docker buildx bake builds many images from one docker-bake.hcl file (or JSON, or a Compose file) in parallel.
  • A target is a build, a group is a list of targets (the default group runs when you name nothing), variables can come from the environment and inherits shares settings.
  • Use --print to preview, --list targets to explore, --check to lint, --set target.field=value to override and --load or --push to choose the output.
  • HCL functions and matrices avoid repeating tag policies and version combinations.
  • The same file serves laptops and CI. Trust the source of any bake file before building it.

Next: Container Lifecycle