Sub topic 4
Trimming the build context with .dockerignore
This chapter assumes you can run docker build and docker run, read a simple Dockerfile, and know that images are built from layers. You should also know that a build can be cached layer by layer. By the end you will know what the build context is, how a .dockerignore file shrinks it, and which mistakes make the file silently fail.
What the build context is
When you run docker build -t myapp ., the final . is the build context. It is the set of files the builder is allowed to read. COPY and ADD can only take files from inside this set.
The builder does not read your directory lazily. With the classic builder, the Docker client packs the whole directory into a tar archive and sends it to the daemon before the first instruction runs. BuildKit, the default builder in current Docker releases, transfers only the files that the Dockerfile actually needs. It still has to scan and filter the directory. Either way, a large or messy context costs you in three ways:
- Time. A project with a 1 GB
node_modulesfolder or a.githistory of several hundred megabytes can make every build slow before any instruction runs, especially with a remote builder. - Cache misses.
COPY . .creates a layer whose cache key depends on the content of every file it copies. If a log file changes on each run, that layer is rebuilt every time, and so is every layer after it. - Accidental inclusion. Anything inside the context can end up in the image. Local
.envfiles, private keys, and editor backups are common examples.
The third point is a security matter, not only a size matter. A secret copied into a layer stays in the image history even if a later instruction deletes it.
Creating a .dockerignore file
The file is named .dockerignore and lives at the root of the build context, next to the Dockerfile in the usual layout. Its syntax looks like .gitignore but is not identical. Each line is a pattern, relative to the context root, naming paths to leave out.
Here is a starting file for a typical Node.js project. It is the same file shown in this tutorial's plan.
.git
node_modules
*.log
.env
Dockerfile
.dockerignoreEach line does a specific job:
| Pattern | What it excludes | Why |
|---|---|---|
| `.git` | The version control directory | It can be large and changes with every commit, which would invalidate `COPY . .`. |
| `node_modules` | Locally installed dependencies | The image installs its own with `npm ci`. Local copies may be built for a different operating system. |
| `*.log` | Log files in the context root | They change constantly and have no use in the image. |
| `.env` | Local environment files | They often hold secrets. |
| `Dockerfile` | The Dockerfile itself | The image rarely needs it. Editing it should not bust the cache for `COPY . .`. |
| `.dockerignore` | The ignore file itself | Same reasoning. |
Excluding Dockerfile and .dockerignore does not stop the builder from using them. The builder reads both files itself, regardless of the filter. The patterns only keep them from being copied into the image by COPY . ..
Pattern rules you need to know
Docker matches patterns using Go's filepath.Match rules with a few additions. These rules cause most of the surprises.
Matching is relative to the context root
A pattern like *.log matches only log files in the root directory. It does not match logs/app.log. To match at any depth, use the ** wildcard:
**/*.log
**/__pycache__
**/.DS_Store** matches any number of directories, including zero. So **/*.log covers both debug.log and logs/app.log.
Excluding a directory excludes its contents
Writing node_modules removes that directory and everything under it. You do not need node_modules/**. Note that node_modules in the root does not exclude packages/web/node_modules. In a monorepo, add **/node_modules.
Exceptions with `!`
A line starting with ! re-includes files that an earlier line excluded. Later lines override earlier ones, so order matters.
*.md
!README.mdThis excludes every Markdown file in the root except README.md. Reversing the two lines would exclude README.md again, because the last matching line wins.
There is a limit to exceptions. If you exclude a parent directory, a later ! line for a file inside it may not behave as you expect in every builder version. When you need one file from an otherwise excluded tree, a safer pattern is to exclude the contents instead of the directory, or to restructure so the needed file lives elsewhere.
The allowlist style
For small projects where you know exactly what the build needs, exclude everything and re-include only what you want. This makes new, unexpected files safe by default.
*
!package.json
!package-lock.json
!src
!tsconfig.jsonThe trade-off is maintenance. When you add a new top-level folder that the build needs, the build fails with a "not found" error until you add an ! line. For teams, that failure is often preferable to a silent secret leak.
Comments and blank lines
Lines starting with # are comments. Blank lines are ignored. A # in the middle of a line is part of the pattern.
A different ignore file for each Dockerfile
BuildKit supports a per-Dockerfile ignore file. If a file named <Dockerfile name>.dockerignore exists next to the Dockerfile, BuildKit uses it instead of the root .dockerignore. For a file called Dockerfile.dev, the matching ignore file is Dockerfile.dev.dockerignore.
This helps when one repository holds several images with different needs. For example, a development image may keep test fixtures that the production image must not contain.
Seeing the effect
You can measure the context size without guessing. With BuildKit, the build output reports how much data was transferred. Look for a line such as transferring context: 1.2MB. Build once before adding a .dockerignore and once after, and compare.
A quick way to see what a COPY . . would bring into the image is to build a throwaway image that lists its working directory.
FROM busybox
WORKDIR /ctx
COPY . .
CMD ["find", ".", "-type", "f"]Save this as Dockerfile.ctx, then run it:
docker build -f Dockerfile.ctx -t ctxcheck .
docker run --rm ctxcheckThe output lists every file that survived the filter. If you still see .env or node_modules in the list, your patterns are not matching. Remove the image afterward with docker rmi ctxcheck.
Because this check uses Dockerfile.ctx, BuildKit will look for Dockerfile.ctx.dockerignore first. If it does not exist, it falls back to .dockerignore, which is what you want to test.
Common errors
- Pattern in the wrong place. The file must be in the context root, not in a subdirectory. If you build with
docker build ./app, the context root is./app, so the file belongs at./app/.dockerignore. - Expecting
.gitignorebehavior. A.gitignorepattern likebuild/without a leading path matches at any depth in Git. In.dockerignore, it matches only at the root unless you write**/build. - Trailing slashes and spaces. A trailing space becomes part of the pattern in some editors. Keep each pattern on its own clean line.
- Ignoring a file that the Dockerfile needs. If you exclude
package-lock.jsonand the Dockerfile runsCOPY package*.json ./, the build fails or silently copies fewer files than you expect. Match your ignore rules to everyCOPYsource. - Assuming the ignore file removes secrets from existing images. It only affects future builds. An image already built with a leaked
.envstill contains it. - Forgetting the multi-stage case. The ignore file applies to the whole build context, for every stage. A file ignored for the build stage is also unavailable to the final stage's
COPYfrom the context. Files copied between stages withCOPY --fromare not affected, because they come from another stage and not from the context.
How it fits with caching
Instruction order and the ignore file work together. A common layout copies the dependency manifests first, installs, and then copies the source:
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .Even with this order, COPY . . still depends on every file it copies. Without a .dockerignore, a changed .git index or a new log file invalidates that layer on each build. With a good ignore file, the layer changes only when real source files change. The ignore file therefore protects the cache in the same way that good ordering does.
Exercise
Your project root contains app.log and logs/debug.log. Your .dockerignore contains only the line *.log. After building with COPY . ., which of these files ends up in the image, and what change makes the filter cover both?
Show answer
logs/debug.log ends up in the image, because *.log matches only files in the context root. app.log is excluded. Replacing the pattern with **/*.log excludes both files, since ** matches any number of directories.
Exercise
A monorepo has node_modules in the root and in packages/web/. The .dockerignore lists node_modules. You then notice the image is still large. What is the likely cause, and how do you fix it?
Show answer
The pattern node_modules matches only the directory in the context root. The copy in packages/web/node_modules is still sent and copied. Add the line **/node_modules so that directories with that name are excluded at every depth.
Exercise
You want to exclude all Markdown files from the context except README.md, which a build step reads. Write the two lines of the .dockerignore, and explain why their order matters.
Show answer
Write *.md first, then !README.md. The last matching line wins, so the ! line re-includes README.md. If you reversed them, *.md would match README.md again and exclude it.