9.3.1 Service Build Config
A focused guide to Service Build Config, connecting core concepts with practical Docker and container operations.
Service build config is the collection of options nested under a service's build field, controlling exactly how Compose constructs that service's image from local source — the build context, which Dockerfile to use, build arguments, and more — beyond the simplest form of just pointing at a directory.
Expanding Build Into Its Full, Structured Form
While build can be a simple path, expanding it into a mapping exposes the full range of configuration options available for constructing the image.
services:
api:
build:
context: .
dockerfile: Dockerfile
args:
- NODE_VERSION=20
target: production
Why Structured Build Config Supports More Sophisticated Build Needs
A simple build: . form is sufficient for a straightforward image build, but more sophisticated needs — multiple Dockerfiles for different purposes, build arguments, multi-stage build targets — require this expanded, structured configuration.
services:
api-dev:
build:
context: .
dockerfile: Dockerfile.dev
api-prod:
build:
context: .
dockerfile: Dockerfile.prod
target: production
Two services here build from the same context directory but use different Dockerfiles and build targets, reflecting their different purposes.
Combining Build With Image to Name the Result
Specifying both build and image together names the resulting built image, making it referenceable and taggable beyond just the service definition itself.
services:
api:
build: .
image: myapi:2.3.0
Triggering a Rebuild That Reflects Updated Build Config
Changing any of these build configuration options requires an explicit rebuild for the change to actually take effect.
docker compose build api
Why Service Build Config Matters
The full range of options available under a service's build field provides the control needed to handle build scenarios more sophisticated than a simple, single Dockerfile build, supporting the variety of build configurations a real-world project's development and production needs often require.