Building Images
When a service has a build section, Compose hands the work to BuildKit, the same builder behind
docker build and docker buildx bake. Everything you know from the Dockerfile and
multi-stage builds lessons still applies; the build section is just a declarative way to
write the build flags down so nobody has to remember them.
compose.yaml build: BuildKit image
context ./api ───────▶ sends ./api (minus .dockerignore) ─▶ shop/api:dev
dockerfile, target, runs the Dockerfile stages
args, secrets, cache with args, secrets, cacheShort and long syntax
build: ./api is shorthand for a context. The long form is a map with many optional keys:
| Key | docker build flag |
Purpose |
|---|---|---|
context |
the path argument | folder (or Git URL) sent to the builder |
dockerfile |
-f |
Dockerfile path, relative to the context |
dockerfile_inline |
-f - |
the Dockerfile itself, written in the Compose file |
target |
--target |
stop at this stage of a multi-stage build |
args |
--build-arg |
values for ARG instructions |
tags |
-t (extra) |
more names for the built image, besides image |
labels |
--label |
metadata on the image |
platforms |
--platform |
build for several CPU architectures |
cache_from / cache_to |
--cache-from / --cache-to |
external build cache |
secrets |
--secret |
secret files for RUN --mount=type=secret |
ssh |
--ssh |
forward your SSH agent for RUN --mount=type=ssh |
additional_contexts |
--build-context |
extra named contexts for COPY --from= |
network, extra_hosts, shm_size |
same names | the environment of RUN steps |
no_cache, pull |
--no-cache, --pull |
ignore the cache, always pull base images |
A typical development/production build
A single Dockerfile with a dev and a runtime stage, and a Compose file that picks the stage and passes
arguments:
# api/Dockerfile.prod
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim AS base
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM base AS dev
CMD ["flask", "--app", "app", "run", "--host", "0.0.0.0", "--debug"]
FROM base AS runtime
ARG GIT_SHA=unknown
LABEL org.opencontainers.image.revision=$GIT_SHA
COPY . .
USER 10001
CMD ["gunicorn", "app:app", "-b", "0.0.0.0:8000"]# $ docker compose config --no-path-resolution
services:
api:
image: shop/api:dev
build:
context: ./api
dockerfile: Dockerfile.prod
target: runtime
args:
- PYTHON_VERSION=3.13
- GIT_SHA
tags:
- "registry.example.com/shop/api:1.4"
labels:
org.example.team: payments
platforms: [linux/amd64, linux/arm64]name: demo
services:
api:
image: shop/api:dev
networks:
default: null
build:
context: ./api
dockerfile: Dockerfile.prod
args:
PYTHON_VERSION: "3.13"
labels:
org.example.team: payments
target: runtime
tags:
- registry.example.com/shop/api:1.4
platforms:
- linux/amd64
- linux/arm64
networks:
default:
name: demo_default
Look at the args. PYTHON_VERSION arrived as a map entry. GIT_SHA was written without a value, which means
"take it from the environment Compose runs in". The example's environment is empty, so the argument was simply
dropped, and the Dockerfile's own default (unknown) will apply. Provide it in a .env file or the shell and it
appears:
# $ docker compose config --no-path-resolution
services:
api:
build:
context: ./api
args:
GIT_SHA:
BUILD_DATE: ${BUILD_DATE:-unknown}
# --- .env
GIT_SHA=4f9c2e1name: demo
services:
api:
networks:
default: null
build:
context: ./api
dockerfile: Dockerfile
args:
BUILD_DATE: unknown
GIT_SHA: 4f9c2e1
networks:
default:
name: demo_default
BUILD_DATE shows the other style: an explicit interpolation with a default.
Both are resolved when Compose reads the file, before BuildKit sees anything.
Build args are not runtime variables
args only exist while the image is built. Unless the Dockerfile copies them into an ENV, the running
container never sees them; runtime values belong in environment. And never pass
passwords as build args: they are recorded in the image history. Use build secrets instead.
Inline Dockerfiles
For small helper images, a separate Dockerfile is overkill. dockerfile_inline keeps it in the Compose file; a YAML
literal block (|) preserves the newlines:
# $ docker compose config --no-path-resolution
# $ docker compose config --images
services:
toolbox:
build:
dockerfile_inline: |
FROM alpine:3.22
RUN apk add --no-cache curl jq postgresql18-client
ENTRYPOINT ["sh"]$ docker compose config --no-path-resolution
name: demo
services:
toolbox:
networks:
default: null
build:
context: .
dockerfile_inline: |
FROM alpine:3.22
RUN apk add --no-cache curl jq postgresql18-client
ENTRYPOINT ["sh"]
networks:
default:
name: demo_default
$ docker compose config --images
demo-toolbox
The context defaulted to ., the project folder, and the image is called demo-toolbox.
Secrets, SSH and extra contexts
# $ docker compose config --no-path-resolution
services:
api:
build:
context: ./api
secrets:
- pip_token
ssh:
- default
additional_contexts:
shared: ../libs/shared
base: docker-image://python:3.13-slim
cache_from:
- type=registry,ref=registry.example.com/shop/api:cache
docs:
build: https://github.com/acme/docs.git#main:site
secrets:
pip_token:
environment: PIP_TOKENname: demo
services:
api:
networks:
default: null
build:
context: ./api
dockerfile: Dockerfile
ssh:
- default
cache_from:
- type=registry,ref=registry.example.com/shop/api:cache
additional_contexts:
base: docker-image://python:3.13-slim
shared: ../libs/shared
secrets:
- source: pip_token
docs:
networks:
default: null
build:
context: https://github.com/acme/docs.git#main:site
dockerfile: Dockerfile
networks:
default:
name: demo_default
secrets:
pip_token:
name: demo_pip_token
environment: PIP_TOKEN
secretsmountspip_token(here read from thePIP_TOKENvariable of the host) only during aRUN --mount=type=secret,id=pip_token …step. It never lands in a layer.ssh: [default]forwards your SSH agent, forRUN --mount=type=ssh git clone git@…of private repositories.additional_contextsgivesCOPY --from=sharedaccess to a folder outside the main context, or swaps a base image (docker-image://) without editing the Dockerfile.- A context can be a Git URL:
#main:sitemeans branchmain, subfoldersite.
A YAML trap: commas in flow lists
cache_from values contain commas. In a YAML flow list ([a, b]) the comma separates items, so the reference
is cut in two:
# $ docker compose config --no-path-resolution
services:
api:
build:
context: ./api
cache_from: [type=registry,ref=registry.example.com/shop/api:cache]name: demo
services:
api:
networks:
default: null
build:
context: ./api
dockerfile: Dockerfile
cache_from:
- type=registry
- ref=registry.example.com/shop/api:cache
networks:
default:
name: demo_default
Two broken entries instead of one. Use a block list (- …) or quote the value.
The build cache in a model
BuildKit reuses a cached layer when the instruction and everything it depends on are unchanged; the first changed
step invalidates every step after it. That is why COPY requirements.txt + pip install come before COPY . ..
The model compares two orders of the same Dockerfile after a code-only change:
def build(steps, changed_files, cache):
invalid = False
out = []
for step, inputs in steps:
key = (step, tuple(sorted(inputs)))
if not invalid and key in cache and not (set(inputs) & changed_files):
out.append(f"CACHED {step}")
else:
invalid = True
out.append(f"RUN {step}")
cache.add(key)
return out
good = [("FROM python:3.13-slim", []), ("COPY requirements.txt", ["requirements.txt"]),
("RUN pip install", []), ("COPY . .", ["app.py", "requirements.txt"])]
bad = [("FROM python:3.13-slim", []), ("COPY . .", ["app.py", "requirements.txt"]),
("RUN pip install", [])]
for name, steps in [("deps first", good), ("copy all first", bad)]:
cache = set()
build(steps, set(), cache) # first build fills the cache
print(name)
for line in build(steps, {"app.py"}, cache): # then edit app.py and rebuild
print(" " + line)deps first
CACHED FROM python:3.13-slim
CACHED COPY requirements.txt
CACHED RUN pip install
RUN COPY . .
copy all first
CACHED FROM python:3.13-slim
RUN COPY . .
RUN RUN pip install
With dependencies first, editing app.py only re-runs the final COPY; the slow pip install stays cached.
Build commands
$ docker compose build # every service with a build section
$ docker compose build --pull --no-cache api # fresh base image, no cache
$ docker compose build --build-arg GIT_SHA=$(git rev-parse --short HEAD)
$ docker compose up -d --build # build what's needed, then start
$ docker compose push api # push image: (and tags:) to the registryLearn more: Services: image & build · Build cache · Compose in CI
Test yourself
An arg is written as GIT_SHA: with no value and the variable is not set anywhere. What happens?
- Compose fails
- The arg is passed as an empty string
- The arg is dropped, so the Dockerfile's ARG default applies
- Compose asks for a value
Why is cache_from: [type=registry,ref=…] wrong?
- cache_from is not a valid key
- In a YAML flow list the comma splits the value into two items
- Registries can't hold cache
- It needs a digest
How should a private package-index token reach the build?
- As a build arg
- As an ENV in the Dockerfile
- As a build secret mounted with RUN --mount=type=secret
- In the image label