Sub topic 10
Keeping the context small with .dockerignore
This chapter assumes you can write a basic Dockerfile and run docker build. It also assumes you know what the build context is and how layers are cached. Here you will use a .dockerignore file to control which files the build can see. That makes builds faster, images smaller, and secrets less likely to leak.
Why the context matters
When you run docker build ., the final . names the build context. The client sends the whole context directory to the builder before any instruction runs. Every COPY and ADD can only read from that set of files.
Without filtering, the context includes everything under the directory. That usually means node_modules, the .git history, logs, local environment files, and build output. This causes three problems:
- Slow builds. A large context takes time to transfer, especially to a remote builder.
- Cache misses.
COPY . .is cached by file content. If any file in the context changes, the layer and every layer after it are rebuilt. A log file that changes on every run can invalidate the cache each time. - Leaked data.
COPY . .places everything it receives into the image. A.envfile or a private key can end up in a layer that you later push to a registry.
A .dockerignore file lists paths to leave out of the context. Excluded files are never sent to the builder. COPY . . cannot copy them, because they are not there.
Creating the file
Put a file named .dockerignore in the root of the build context, next to the Dockerfile. If you build with -f and a Dockerfile elsewhere, the .dockerignore file is still read from the context root. BuildKit also supports a per-Dockerfile file named <Dockerfile name>.dockerignore next to the Dockerfile. It takes precedence over the root .dockerignore.
Here is the file used with the Node.js example in this tutorial:
node_modules
.git
*.log
.env
Dockerfile
.dockerignoreEach line is a pattern, and each pattern excludes something:
| Pattern | Why it is excluded |
|---|---|
| `node_modules` | Local dependencies may be built for your host OS. The image installs its own with `npm ci`. |
| `.git` | Version control history is large and not needed at runtime. |
| `*.log` | Logs change often and would invalidate the cache. |
| `.env` | Local secrets must not be copied into an image. |
| `Dockerfile` and `.dockerignore` | The image does not need its own build files. |
Excluding Dockerfile and .dockerignore is optional. The builder still reads them even when they are excluded. They are simply not available to COPY.
Pattern syntax
The syntax is similar to .gitignore, but it is not identical. Paths are relative to the context root, and a pattern is matched against the whole path from that root.
- A plain name such as
node_modulesmatches that name only at the root of the context. It does not matchpackages/app/node_modules. *matches any run of characters within one path segment.*.logmatchesdebug.logat the root, but notlogs/debug.log.?matches a single character.**matches any number of directories, including none.**/*.logmatches log files at every depth.- Lines starting with
#are comments. - A line starting with
!is an exception that re-includes paths excluded by earlier patterns.
The first two rules differ from .gitignore, where an unanchored name matches at any depth. In a .dockerignore file, you must write **/node_modules to exclude it everywhere.
# Dependencies at any depth
**/node_modules
# Logs at any depth
**/*.log
# Local environment files, but keep the template
.env*
!.env.example
# Build output
dist
coverageExceptions and ordering
Patterns are evaluated in order, and the last matching pattern decides the outcome. An exception must therefore come after the pattern it overrides.
A common technique is to exclude everything and then list what the build needs. This is an allowlist:
*
!package.json
!package-lock.json
!server.js
!srcAn allowlist is the safest style. New files, such as a stray credentials file, are excluded by default until you add them. The cost is maintenance. If you add a new top-level directory and forget to list it, the build fails or produces an incomplete image.
An exception does not work if its parent directory is excluded and you only name a file inside it in a way that no longer matches. Test any nested exceptions rather than assuming they work. The check shown later in this chapter makes that easy.
Seeing the effect
You can see the context size in the build output. With BuildKit, look for the line that transfers the context:
docker build -t myapp:1.0 .The output includes a line like this:
=> [internal] load build context
=> => transferring context: 412.31MBAfter you add a .dockerignore file that excludes node_modules and .git, the same line might show a few hundred kilobytes. The size difference is the quickest way to confirm the file is working.
To see exactly which files reach the image, build a throwaway image that lists the context. This Dockerfile copies everything the builder receives and prints it:
FROM busybox
WORKDIR /ctx
COPY . .
CMD ["find", ".", "-type", "f"]Save it as Dockerfile.ctx in the project root, then build and run it:
docker build -f Dockerfile.ctx -t ctx-check .
docker run --rm ctx-checkThe output lists every file that survived your .dockerignore. If .env or node_modules appears, a pattern is wrong. Remove the image afterward with docker rmi ctx-check.
If you use this check, remember that the root .dockerignore excludes Dockerfile by default in the earlier example. Dockerfile.ctx is a different name, so it is unaffected. It still gets read by the builder, and it is copied into the listing unless you exclude it.
How it interacts with the cache
Consider the cache-friendly Node.js Dockerfile from the earlier chapters:
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]The first COPY copies only the dependency manifests. The npm ci layer stays cached as long as those two files do not change. The second COPY . . brings in the rest of the source.
.dockerignore protects both steps:
- Without it,
COPY . .also copies your hostnode_modules. It overwrites the directory thatnpm cijust created in the image. The host copy may contain binaries compiled for a different operating system or CPU architecture, and the app can fail at runtime. - Files such as
*.logor editor swap files change often. Each change invalidates theCOPY . .layer, so everything after it rebuilds.
Excluded files do not count toward cache keys. A change to an ignored file does not invalidate any layer.
Common mistakes
- Unanchored patterns. Writing
node_modulesand expecting it to match in subdirectories. In a monorepo, use**/node_modules. - Excluding a file the Dockerfile needs. If you exclude
package-lock.jsonand your Dockerfile runsCOPY package*.json ./,npm cifails because it requires the lock file. The error appears at theCOPYorRUNstep, not at the pattern that caused it. - Wrong location. The file must be at the context root. A
.dockerignorefile in a subdirectory is ignored unless that subdirectory is the context. - Wrong order of exceptions. Putting
!.env.examplebefore.env*has no effect, because the later pattern excludes it again. - Assuming it hides secrets from everything. It only filters the context. A secret passed through
ARG, or written by aRUNstep, still lands in the image history. Use BuildKit secret mounts for that case. - Trailing slashes and paths. Patterns use forward slashes on all platforms. Leading slashes are ignored, so
/distanddistmean the same thing.
A practical starting point
For a typical project, start with the patterns below and adjust them to the language you use:
# Version control
.git
.gitignore
# Dependencies installed inside the image
**/node_modules
**/__pycache__
.venv
# Secrets and local config
.env*
!.env.example
*.pem
# Logs and temporary files
**/*.log
tmp
# Build output and test artifacts
dist
build
coverage
# Docker files
Dockerfile*
.dockerignoreThen run the context check from earlier. Compare the listing against what your Dockerfile needs. Remove patterns that exclude required files, and add patterns for anything you see that should not be there.
Exercise
Your project has packages/api/node_modules and packages/web/node_modules. Your .dockerignore contains the line node_modules, yet the build context is still large. Why, and what line fixes it?
Show answer
A plain node_modules pattern is matched against the path from the context root, so it only excludes the top-level node_modules directory. The nested ones are still sent. Replace it with **/node_modules, which matches the directory at any depth.
Exercise
Your .dockerignore contains .env* on one line and !.env.example above it. You expect .env.example to be in the context. Is it? How do you fix it?
Show answer
No. Patterns are evaluated in order and the last match wins, so .env* placed afterward excludes .env.example again. Put !.env.example after .env*.