Sub topic 5
The build context and .dockerignore
This chapter assumes you can run docker build and write a basic Dockerfile with FROM, COPY, and RUN. It explains what Docker sends to the builder when you build, how .dockerignore shapes that, and the errors that come from getting it wrong.
What the build context is
The build context is the set of files that a build can read from your machine. When you run docker build -t myapp:1.0 ., the final argument (.) is the context root. Docker packages the files under that directory and makes them available to the builder. Only files inside the context can be used by COPY and ADD.
The Dockerfile is normally found at the root of the context, but it does not have to be. The -f flag selects a different Dockerfile, and the context still comes from the last argument.
docker build -f docker/Dockerfile.prod -t myapp:1.0 .Here the context is the current directory, and the Dockerfile lives in docker/.
A context can also be a Git repository URL or a tarball. This chapter focuses on local directories, because they are the common case.
Why context size matters
With the classic builder, the whole context is sent to the Docker daemon before the first instruction runs. With BuildKit, the current default builder, only the files an instruction actually needs are transferred. Even so, a large context causes problems:
- Slow builds, especially when the daemon is remote or the context is large.
- Cache invalidation. A
COPY . .instruction depends on the content of every file it copies, so a change to any of them invalidates that layer and all later layers. - Accidental inclusion of files that should never be in an image, such as
.githistory,.envfiles, and private keys.
The last point is the serious one. Anything copied into a layer stays in the image, and anyone who can pull the image can extract it.
Writing a .dockerignore file
A .dockerignore file sits at the root of the context. Docker reads it before the build and excludes matching paths from the context. Excluded files cannot be copied, and changes to them do not invalidate the cache.
.git
node_modules
*.log
.envThis is the example from the topic plan. It excludes version-control data, locally installed dependencies, log files, and a secrets file.
Pattern rules
The syntax is similar to .gitignore but not identical. Patterns are matched relative to the context root.
| Pattern | Meaning |
|---|---|
| `*.log` | Matches `.log` files in the root directory only. |
| `**/*.log` | Matches `.log` files at any depth. |
| `temp?` | `?` matches exactly one character, such as `temp1`. |
| `docs` | Matches the `docs` file or directory at the root. |
| `!README.md` | An exception: re-includes a path an earlier rule excluded. |
Two details cause most surprises:
- A pattern such as
*.logdoes not reach into subdirectories. Use**/*.logfor that, as the*wildcard does not cross directory separators. - Order matters. The last matching rule wins, so an exception must come after the rule it overrides.
# Exclude all markdown files, but keep the top-level README
*.md
!README.mdA common allowlist style excludes everything and then re-includes only what the build needs. It is strict, and it protects against new files being added by accident.
*
!go.mod
!go.sum
!cmd
!internalNote that if you exclude a directory and then re-include a file inside it, the exception may not work as you expect, so test it. The way to check is to look at what actually arrives in the image, as shown below.
A separate ignore file per Dockerfile
With BuildKit, you can give each Dockerfile its own ignore file by naming it after the Dockerfile with a .dockerignore suffix. For docker/Dockerfile.prod, that is docker/Dockerfile.prod.dockerignore. If present, it takes precedence over the root .dockerignore. This helps when one repository holds several images with different needs.
Context and the Dockerfile itself
The Dockerfile and .dockerignore are sent to the builder even if you list them in .dockerignore. The builder needs the first to know what to do. Listing them only stops COPY from copying them into the image.
Context and the build cache
The context interacts with the cache through COPY and ADD. For each such instruction, Docker computes a checksum of the files being copied. If the checksum matches a previous build, the cached layer is reused.
This is why the Dockerfile in this tutorial copies dependency files first:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The first COPY involves only two files, so the go mod download layer stays cached until dependencies change. The second COPY . . pulls in everything else in the context. A good .dockerignore limits that to source code, so editing a log file or switching Git branches (which rewrites .git) does not trigger a rebuild.
Inspecting what ends up in the image
To check what a broad COPY actually included, build a throwaway image that lists the context. This approach works with any builder.
FROM busybox
WORKDIR /ctx
COPY . .
RUN find . -type f | sortSave it as Dockerfile.ctx and run:
docker build -f Dockerfile.ctx --no-cache --progress=plain .The --progress=plain flag prints the find output in the build log. Compare the list with what you expected. Note that the build still uses your .dockerignore, so the list reflects the filtered context.
Common errors
COPY failed: file not found in build context. The path is wrong, is outside the context, or is excluded by.dockerignore. Paths inCOPYare relative to the context root, not to the Dockerfile. A path like../config.yamlcannot be reached because it is above the root.- Building with the wrong context. Running
docker build .from a subdirectory makes that directory the root, so sibling directories are invisible. Run the build from the repository root and pass-fto select the Dockerfile. - A huge context from running
docker build /or from your home directory. The builder tries to read everything. Always check the final argument. - A rule that excludes too much. A broad pattern such as
*.jsonremovespackage.json. Add an exception (!package.json) or narrow the pattern. - The cache is invalidated on every build. A frequently changing file, such as a build output directory or an editor swap file, is part of what
COPY . .copies. Add it to.dockerignore.
Putting it together
The diagram shows how the context moves from your disk into a build.
In short, the context decides what the build can see, .dockerignore narrows that view, and the narrowed set decides both image contents and cache behavior.
Exercise
Your build runs COPY . . and the cache is invalidated on every build, even when you change no source code. The project has a logs/ directory that the application writes to during local testing. What do you add to .dockerignore, and why does it fix the problem?
Show answer
Add logs (or **/*.log if the logs are scattered). The COPY . . instruction checksums every file it copies, and the log files change constantly, so the checksum differs on each build and the layer is rebuilt. Once the files are excluded from the context, they no longer count toward the checksum, and the layer is reused when the source is unchanged. It also keeps log contents out of the image.
Exercise
A .dockerignore contains *.md followed by !README.md. A second one lists !README.md first and *.md second. In which case is README.md part of the context, and what rule explains it?
Show answer
In the first case. When several patterns match a path, the last matching rule wins. In the first file the exception comes last, so README.md is re-included. In the second file *.md comes last and excludes it again.