9.3.1.1 Compose Build Context
A focused guide to Compose Build Context, connecting core concepts with practical Docker and container operations.
The Compose build context is the directory whose contents are sent to the Docker build process and made available for COPY and ADD instructions within the Dockerfile, specified through the context field within a service's build configuration.
Specifying the Build Context
The context field points to the directory that should serve as the build's source of files.
services:
api:
build:
context: ./backend
Only the contents of ./backend are available to the build process; files outside this directory cannot be referenced by COPY or ADD instructions in the corresponding Dockerfile.
Why Build Context Size Matters
Every file within the specified context directory is sent to the Docker build process at the start of a build, regardless of whether the Dockerfile actually references it — an unnecessarily large or cluttered context directory slows down every build, even when most of its content is never actually used.
.dockerignore
node_modules
.git
*.log
A .dockerignore file excludes irrelevant content from being sent as part of the build context, meaningfully improving build performance for a context directory that would otherwise include a lot of unnecessary content.
Using a Different Context Than the Service's Own Directory
A service's build context doesn't need to match where its Dockerfile resides — a multi-service project might use a shared, broader context for several related services.
services:
api:
build:
context: .
dockerfile: ./backend/Dockerfile
Here, the build context is the entire project root, while the actual Dockerfile used resides in a specific subdirectory.
Why the Compose Build Context Matters
Correctly specifying and appropriately scoping the build context is essential both for the build to have access to exactly the files it needs, and for keeping build performance reasonable by avoiding unnecessarily large or unfiltered context directories.