Sub topic 3
The build context
This chapter covers the build context: what it is, how Docker sends it to the builder, how COPY relies on it, and the errors that come from misunderstanding it. It assumes you can run docker build, you know the basic Dockerfile instructions, and you know that an image is built from a Dockerfile.
What the build context is
When you run docker build, the last argument is the build context. It is the set of files the builder is allowed to read while building the image.
docker build -t myapp:1.0 .The . here is the context path. Docker packages the directory at that path, and everything inside it, and makes it available to the builder. The build client talks to a builder, which may be the local Docker daemon, BuildKit, or a remote machine. Because the builder may not be on your machine, it cannot read your disk freely. It can only see what the client sends.
This has three consequences:
COPYandADDcan only reference files inside the context.- Files outside the context do not exist as far as the build is concerned.
- Large contexts slow the build, because the client has to send them.
The context is not the Dockerfile's folder
Two things are easy to confuse: the context and the Dockerfile location. By default, Docker looks for a file named Dockerfile at the root of the context. You can point to a different file with -f.
docker build -f docker/Dockerfile.prod -t myapp:prod .Here the context is still ., the current directory. The Dockerfile lives in docker/, but COPY paths are resolved against the context root, not against docker/.
| Part of the command | What it controls |
|---|---|
| `-f path` | Which file holds the instructions |
| Last argument | Which directory is the context |
| `COPY src dest` | `src` is relative to the context root |
How COPY uses the context
In COPY <src> <dest>, the source is a path inside the context. The destination is a path inside the image, resolved against the current WORKDIR if it is relative.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]The first COPY takes package.json and package-lock.json from the context root and places them in /app. The second COPY . . copies the whole context into /app. The first dot means the context root. The second dot means the current WORKDIR.
Whatever is in the context at the time of the second COPY ends up in the image. If your context contains .env, .git, or node_modules, they will be copied too, unless you exclude them.
Paths that escape the context
You cannot copy files from outside the context. This fails:
COPY ../shared/config.json /app/The builder reports an error such as forbidden path outside the build context. Docker also rejects absolute host paths such as COPY /home/me/file /app/, because an absolute source is still resolved inside the context, so that path does not exist there.
The fix is to choose a context that contains everything you need. If shared/ sits next to your app directory, make the parent directory the context and point to the Dockerfile with -f:
docker build -f app/Dockerfile -t myapp:1.0 .Then use paths relative to that parent:
COPY app/ /app/
COPY shared/config.json /app/config.jsonTypes of context
The context path can be more than a local directory.
| Context | Example | Notes |
|---|---|---|
| Local directory | `docker build .` | The most common case |
| Git repository | `docker build https://github.com/org/repo.git#main` | The builder clones the repository and uses it as the context |
| Remote tarball | `docker build https://example.com/ctx.tar.gz` | The builder downloads and unpacks it |
| Standard input | `docker build - < Dockerfile` | Only the Dockerfile is sent, so `COPY` cannot read local files |
A Git context can select a branch and a subdirectory with #ref:subdir, for example #main:docker. For private repositories you need to give the builder credentials, and that setup depends on your Docker version and builder.
The standard input form is useful for quick experiments with a Dockerfile that has no COPY from the host. If you pipe a Dockerfile and then use COPY . ., there is nothing to copy.
What gets sent, and why size matters
With the classic builder, the client uploads the whole context to the daemon at the start of every build. You see a line like this in the output:
Sending build context to Docker daemon 412.6MBBuildKit, the default builder in current Docker releases, is smarter. It transfers only the files a build step actually needs and caches what it has already sent. Its output shows a step named load build context with a transferred size.
Even so, a large context costs you:
- Time to scan and hash the files, even if they are not transferred.
- Time to transfer files that are used, especially with a remote builder.
- Cache invalidation, because a changed file that
COPY . .touches changes that layer. - Risk of leaking files such as
.envor private keys into an image layer.
The usual offenders are node_modules, .git, build output, logs, virtual environments, and local data files.
Controlling the context with .dockerignore
A .dockerignore file at the context root lists paths that the builder should leave out of the context. Excluded files are not available to COPY at all.
node_modules
.git
*.log
.env
Dockerfile
.dockerignoreEach line is a pattern, similar to .gitignore but not identical. Key points:
- Patterns are relative to the context root.
*matches within one directory level, and**matches across directories.- A line starting with
!re-includes a path that an earlier line excluded. - Lines starting with
#are comments.
Excluding Dockerfile and .dockerignore keeps them out of COPY . .. Docker still reads them to run the build. The exclusion only hides them from COPY and ADD, so changes to them no longer invalidate the COPY . . layer.
A later chapter covers .dockerignore in more detail. For now, remember that it shapes the context, and that a good one is often the cheapest build speedup you can make.
Allowlist style
If your project has many files and the image needs only a few, exclude everything and re-include what you need:
*
!package.json
!package-lock.json
!src/
!server.jsThis reverses the default. New files do not enter the image until you add them, which prevents accidents. Order matters: the last matching line wins.
Where the context fits in the build
The filter runs before anything else. After it, the builder works with the filtered set of files only.
Common errors
File not found during COPY
failed to compute cache key: "/config/app.json": not foundThis message usually has one of three causes:
- The path is wrong. Check it against the context root, not against the Dockerfile's folder.
- The file is excluded by
.dockerignore. Check the patterns, including broad ones such as*.jsonorconfig. - The context root is not what you think. Check the last argument to
docker build, and check the directory where you ran the command.
A quick way to see what the builder receives is to copy the context into a temporary image and list it:
FROM busybox
COPY . /ctx
RUN find /ctx -type fBuild it with docker build --no-cache --progress=plain . and read the file list in the output. Delete this Dockerfile afterward.
Slow builds with a tiny change
If a one-line code change causes a long "load build context" step, the context probably contains large directories. Check with:
du -sh * .[!.]* 2>/dev/null | sort -hAdd the largest entries that the image does not need to .dockerignore.
Secrets in the image
If .env or a key file is in the context and COPY . . copies it, the secret is stored in an image layer. Deleting it later with RUN rm .env does not remove it from the earlier layer, and anyone with the image can extract it. Exclude secrets from the context, and for build-time secrets use BuildKit secret mounts, which a later chapter covers.
Symlinks
A symlink in the context that points outside the context does not work as you might hope. The builder copies the link itself, not the file it targets, and the link will be broken inside the image. Copy the real file into the context instead.
Choosing a context: decision rules
- Use the smallest directory that contains every file the Dockerfile needs.
- In a monorepo, use the repository root as the context only if you need shared code. Pair it with a strict
.dockerignore, ideally an allowlist. - Keep one
Dockerfileper image and select it with-fwhen several share a context. - If you use BuildKit, a Dockerfile-specific ignore file named
<Dockerfile name>.dockerignoreplaced next to the Dockerfile can override the root.dockerignorefor that build. For example,docker/Dockerfile.prod.dockerignoreapplies to-f docker/Dockerfile.prod.
Exercise
Your project has this layout: services/api/Dockerfile, services/api/main.py, and libs/common/util.py. The Dockerfile contains COPY ../../libs/common/util.py /app/, and the build fails. What should you change so that the Dockerfile can copy both main.py and util.py? Give the build command and the two COPY lines.
Show answer
Make the repository root the context, because COPY cannot read outside it. Run docker build -f services/api/Dockerfile -t api:1.0 . from the repository root. Then use COPY services/api/main.py /app/main.py and COPY libs/common/util.py /app/util.py. Both source paths are relative to the context root. Adding a .dockerignore at the root keeps unrelated files out of the context.
Exercise
A build prints "/config/app.json": not found even though config/app.json exists in your project directory. Name two likely causes and how you would check each.
Show answer
First, .dockerignore may exclude the file, for example through a pattern such as config or *.json. Check by reading the .dockerignore file for matching patterns. Second, the context root may not be the directory you expect, because of the path given to docker build. Check by confirming the last argument and the directory you ran the command from, or by copying the context into a temporary image and listing it with find.