Docker Bake
All examples can be found in this repo here
What is Docker Bake?
As stated in the documentation,
Bake is a
wrapper around the docker build
command that allows you to define how to
build a Docker image.
Bake also lets you build multiple images in parallel, for multiple
platforms, create multiple tags on the same image, build the same image with different build-arg
values…
And all this thanks to one file and a single Docker command.
It is possible to configure your Bake build using different file formats: JSON, Compose, and HCL.
In the rest of this post, all examples will be in HCL.
Scenario
Let’s imagine I need to build a Docker image with different arguments.
The easiest way for me would be to write a Bash script that runs 3 docker
commands, passing those arguments.
Something like this:
#!/bin/bash
set -eu
echo "START BUILDING IMAGES"
base_image_tag="base-image"
child_images_tag=("toto" "tata" "titi")
docker build -t $base_image_tag .
for child_tag in "${child_images_tag[@]}"
do
docker build -f child.dockerfile \
-t "$child_tag-image" \
--build-arg CMD_ARG=$child_tag \
--build-context baseapp="docker-image://$base_image_tag" \
.
done
echo "DONE"
Note that we use a build context to enable inheritance between the base image and its children.
“Job done”, it’s settled, time to clock out. Yes, but here the example is obviously simpler than what you might really need.
Imagine each image takes 4 minutes to build. Here, I would wait 12 minutes in total. Whereas using Bake, I could parallelize my builds, knowing that Bake also tries to optimize layer caching between each build.
HCL equivalent of the Bash script
group "default" {
targets = [
"base",
"childs"
]
}
target "base" {
dockerfile = "Dockerfile"
context = "."
tags = [
"base-image"
]
}
target "childs" {
name = "image-${tag}"
dockerfile = "child.dockerfile"
contexts = {
baseapp = "target:base"
}
tags = [
"${tag}-image"
]
args = {
CMD_ARG = "${tag}"
}
matrix = {
tag = [
"toto",
"tata",
"titi"
]
}
}
Then all I need to do is run the command, and my four images will be built.
docker buildx bake
Should I change all my Bash scripts?
Honestly, if you don’t feel the need to speed up your image builds, then you probably don’t need to waste your time migrating to Bake (after all, it’s always fun to learn).
Bake offers much more than what’s presented in this brief blog post, and I encourage you to check out the official documentation to discover: targets, groups, variables, functions, matrices, and much more.