Skip to main content

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

Bash
docker build . # current directory
docker build -f Dockerfile.prod . # other Dockerfile, same context
docker build -f docker/Dockerfile ./services/api
docker build https://github.com/myorg/myrepo.git#main
cat Dockerfile | docker build - # no files, so no COPY of local paths

Three levels of control

  • Context path: which directory is sent.
  • .dockerignore: which files inside it are excluded from sending.
  • COPY instructions: which context files end up in an image layer.
Dockerfile
# Specific copies keep the image clean
COPY src/ /app/src/
COPY package.json package-lock.json /app/

See the cost

Bash
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 Mistake

Thinking .dockerignore controls the image contents. It controls what is sent. Use specific COPY paths to control layers.

Tip

In monorepos, set the context to the service folder or use .dockerignore rules 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.

Found a mistake, an outdated step or a broken link?