Docker Context
The Docker build context is the set of files at the path or URL you pass to docker build, sent to the builder so COPY and ADD can use them. A small, well-scoped context makes builds faster and safer.
What the build context is
In docker build ., the final . is the context. The CLI sends that directory (minus .dockerignore matches) to the builder before running instructions, because the builder may be remote. COPY and ADD can only read files inside the context. Do not confuse this with the separate docker context command, which switches which Docker daemon the CLI talks to.
Choosing a context
docker build . # current directorydocker build -f Dockerfile.prod . # other Dockerfile, same contextdocker build -f docker/Dockerfile ./services/apidocker build https://github.com/myorg/myrepo.git#maincat Dockerfile | docker build - # no files, so no COPY of local pathsThree levels of control
- Context path: which directory is sent.
.dockerignore: which files inside it are excluded from sending.COPYinstructions: which context files end up in an image layer.
# Specific copies keep the image cleanCOPY src/ /app/src/COPY package.json package-lock.json /app/See the cost
docker build --progress=plain . 2>&1 | grep "transferring context"Troubleshooting
| Problem | Cause | Fix |
|---|---|---|
| Slow before first step | Huge context | Add .dockerignore |
COPY says file not found |
Ignored or outside context | Fix patterns or context path |
| Secrets in image | .env in context and copied |
Ignore it and copy specific paths |
Common MistakeThinking
.dockerignorecontrols the image contents. It controls what is sent. Use specificCOPYpaths to control layers.
TipIn monorepos, set the context to the service folder or use
.dockerignorerules plus a named context with Buildx.
Frequently Asked Questions
Why does a large context slow builds before any step runs?
The CLI must package and transfer the whole context to the builder first. If node_modules, .git, or build outputs are included, hundreds of megabytes move on every build, especially painful with a remote builder.
What is the difference between the build context and docker context?
The build context is the directory sent for one build. The docker context command manages saved connection settings that decide which Docker endpoint the CLI uses, such as a remote host.
How do I stop COPY . . from copying secrets?
Add .env and key files to .dockerignore, and prefer specific COPY paths instead of copying the entire context.