Sub topic 8
Keeping the build context small with .dockerignore
This chapter assumes you can write a simple Dockerfile and run docker build. It also assumes you know that COPY invalidates the cache when its inputs change, as covered in the earlier chapters on cache hits and misses. Here you will see what the build context is, why it affects both build speed and cache behavior, and how to control it with .dockerignore.
What the build context is
The build context is the set of files that a build can read from your project. When you run this command, the final . is the context:
docker build -t myapp:dev .The Docker client packages the files in that directory and makes them available to the builder. Every COPY and ADD instruction that takes a local source path reads from the context. A file outside the context cannot be copied. Paths such as COPY ../secret.txt . fail for this reason.
The context is not the same as what ends up in the image. It is the pool of files the build may use. The image only contains what your instructions copy out of that pool.
Why a large context hurts
A large context causes three separate problems.
- Slow starts. With the legacy builder, the whole context is sent to the daemon before the first instruction runs. With BuildKit, only the files that instructions request are transferred, and later builds send only changes. A large context still costs time on the first build, on a fresh CI runner, and when the builder is remote.
- Needless cache misses.
COPY . .records a checksum of the files it copies. If any copied file changes, that step misses and every later step rebuilds. A changing log file, editor swap file, or the.gitdirectory can trigger this even though the application did not change. - Leaked files.
COPY . .copies everything it can see. If.env, private keys, or local credentials are in the context, they can end up in an image layer. A laterrmdoes not remove them from that layer, as the chapter on layer size pitfalls explained.
flowchart LRThe diagram below shows the path from the project directory to the image, and where .dockerignore filters.
Seeing the size of your context
BuildKit prints the context transfer near the start of the build output. Look for a line like transferring context: 184.32MB. A number in the hundreds of megabytes for a small project usually means a dependency directory, build output, or version-control history is being included.
You can also check what is in the directory before building:
du -sh .
du -sh .git node_modules dist 2>/dev/nullIf .git or node_modules dominate, they are the first candidates to ignore.
Writing a .dockerignore file
Place a file named .dockerignore at the root of the context, next to where you run docker build. Each line is a pattern, relative to the context root. Lines that start with # are comments.
# Version control
.git
.gitignore
# Dependencies installed on the host
node_modules
# Build output and logs
dist
*.log
# Local secrets and environment files
.env
.env.*
# Editor and OS files
.vscode
.DS_Store
# Docker files that the image does not need
Dockerfile
.dockerignore
docker-compose*.ymlDocker reads this file before it sends the context, so ignored files are never transferred and never visible to COPY.
Pattern rules
The syntax looks like .gitignore but differs in important ways.
| Pattern | Meaning |
|---|---|
| `node_modules` | Excludes the `node_modules` file or directory at the context root only. |
| `*.log` | Excludes `.log` files in the root directory only. |
| `**/*.log` | Excludes `.log` files at any depth. |
| `*/temp*` | Excludes files starting with `temp` in any direct subdirectory of the root. |
| `temp?` | Excludes names such as `tempa` and `tempb` in the root. `?` matches one character. |
| `!keep.log` | An exception. Re-includes a file that an earlier pattern excluded. |
Two details cause most mistakes:
- Patterns are anchored at the context root. A plain
*.logdoes not matchlogs/app.log. In.gitignore, a pattern without a slash matches at any depth. Here it does not. Use**/when you want any depth. - The last matching line wins. An exception only works if it comes after the pattern it overrides.
*.md
!README.mdThis excludes all Markdown files in the root except README.md. If you reverse the two lines, README.md is excluded, because the later *.md line wins.
Allowlist style
If the project directory holds many unrelated files, it is easier to exclude everything and then list what the build needs:
*
!package.json
!package-lock.json
!src
!tsconfig.jsonA new file added to the project is then ignored by default and cannot cause a surprise cache miss or an accidental leak. The trade-off is that you must update the list when the build starts to need a new file, and the failure appears as a COPY error such as "/scripts": not found.
How .dockerignore improves the cache
Consider the Dockerfile from the chapter on instruction ordering:
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]The first COPY names only the manifests, so editing source code leaves it cached. The second, COPY . ., takes the whole context. Without .dockerignore, it also copies .git, node_modules, dist, and log files. Each commit changes .git, so the COPY . . layer misses on every build, even when no source file changed. With .git and dist ignored, the layer misses only when real inputs change.
Ignoring node_modules has another benefit. A host installation may contain native modules compiled for a different operating system or CPU. Copying them over the result of npm ci can break the app at runtime. The same logic applies to Python __pycache__ directories and virtual environments.
Things that surprise people
Ignored files cannot be copied
If a file matches a .dockerignore rule, COPY fails to find it. A common case is ignoring *.md and then writing COPY README.md .. Add an exception, or stop ignoring that file.
Ignoring the Dockerfile
You can list Dockerfile and .dockerignore in the file. Docker still sends them to the builder because it needs them to run the build. COPY and ADD will not copy them into the image. This keeps them out of the final filesystem and out of the checksum of COPY . ., so editing the Dockerfile does not invalidate the copy layer by itself.
A different ignore file per Dockerfile
With BuildKit, a file named after the Dockerfile takes priority. If you build with -f build/api.Dockerfile, Docker looks for build/api.Dockerfile.dockerignore first and falls back to the root .dockerignore. This lets one repository hold several images with different contexts.
docker build -f services/api/Dockerfile -t api:dev .For this command, the per-Dockerfile file would be services/api/Dockerfile.dockerignore.
Ignoring does not delete anything
.dockerignore filters what the build can see. It does not touch your files on disk. It also has no effect on docker run -v bind mounts, which read directly from the host.
Using a smaller context directly
Another option is to point the build at a subdirectory, such as docker build -t api:dev services/api. Everything outside it is then unreachable. Use this when a project has independent parts, and use .dockerignore when files you want to exclude sit inside the directory you must build from.
A checklist for a new project
- Run the build once and note the
transferring contextsize. - Add
.git, dependency directories, build output, logs, and env files. - Rebuild and check that the size dropped and that no
COPYnow fails. - Run the build twice without changing anything. Every step should report as cached. If the
COPY . .step still misses, an ignored-worthy file is changing, for example a generated timestamp file. - Check the final image for files that should not be there:
docker run --rm myapp:dev ls -la /appFor a distroless or minimal image without ls, create a temporary container and use docker cp or docker export to inspect it.
Exercise
Your .dockerignore contains the line *.log, yet logs/app.log is still in the build context. Why does this happen, and what single line fixes it?
Show answer
Patterns are anchored at the context root, so *.log only matches .log files in the root directory. Use **/*.log to match at any depth. Note that a line logs would also work if you want to exclude the whole directory.
Exercise
A build has COPY . . followed by an expensive RUN npm run build. The step reruns on every build even when you change no source files. The project is a Git repository with no .dockerignore. What is the likely cause, and how do you confirm the fix?
Show answer
The .git directory changes with every commit, fetch, or index update, so the checksum of COPY . . changes and the layer and all later steps miss. Add .git to .dockerignore. To confirm, run the build twice with no changes and check that the COPY . . and RUN npm run build steps are reported as cached on the second run.