TExcelTAD
Home › Docker › The .dockerignore File

The .dockerignore File

When you run docker build ., the builder can read every file in the build context. A .dockerignore file in the root of the context lists files and folders to leave out. It works much like .gitignore and has three benefits:

  1. Faster builds: less data to transfer to the builder (think node_modules, .git, datasets).
  2. Better caching: COPY . . no longer changes when an unrelated file (a log, an editor swap file) changes.
  3. Safety: secrets such as .env or id_rsa cannot end up in an image by accident.
text
# .dockerignore
.git
.gitignore
node_modules
**/__pycache__
*.log
.env
.env.*
!.env.example
dist/
coverage/
Dockerfile
compose*.yaml

The pattern rules

Pattern Matches
node_modules node_modules at the root of the context (and everything inside it)
*.log .log files at the root only (* does not cross /)
**/*.log .log files in any folder
docs/*.md Markdown files directly inside docs/
!README.md an exception: include it again even though an earlier pattern excluded it
# comment ignored line

When several lines match, the last matching line wins. That is how !.env.example re-includes one file after .env.* excluded all of them.

Note: unlike .gitignore, a plain pattern such as node_modules or *.log is anchored at the root. To ignore it in every subfolder, write **/node_modules or **/*.log.

A .dockerignore matcher

The model translates patterns to regular expressions using the same rules (anchored at the root, * within one path segment, ** across segments, ! exceptions, last match wins), then filters a project.

python · try it yourself
import re

def to_regex(pattern):
    pattern = pattern.strip("/")
    out, i = "", 0
    while i < len(pattern):
        if pattern.startswith("**/", i):
            out += "(?:.*/)?"
            i += 3
        elif pattern.startswith("**", i):
            out += ".*"
            i += 2
        elif pattern[i] == "*":
            out += "[^/]*"
            i += 1
        elif pattern[i] == "?":
            out += "[^/]"
            i += 1
        else:
            out += re.escape(pattern[i])
            i += 1
    return re.compile(out + "(?:/.*)?
quot;) # a match on a folder covers its contents def load(text): rules = [] for line in text.splitlines(): line = line.strip() if not line or line.startswith("#"): continue negate = line.startswith("!") rules.append((negate, to_regex(line.lstrip("!")))) return rules def ignored(path, rules): result = False for negate, regex in rules: if regex.match(path): result = not negate # last match wins return result DOCKERIGNORE = """ .git node_modules **/__pycache__ *.log .env* !.env.example """ project = [".git/config", ".env", ".env.production", ".env.example", "app.log", "logs/today.log", "node_modules/react/index.js", "src/app.py", "src/__pycache__/app.cpython-312.pyc", "README.md"] rules = load(DOCKERIGNORE) for path in project: print(f"{'skip' if ignored(path, rules) else 'send'} {path}")
skip  .git/config
skip  .env
skip  .env.production
send  .env.example
skip  app.log
send  logs/today.log
skip  node_modules/react/index.js
send  src/app.py
skip  src/__pycache__/app.cpython-312.pyc
send  README.md

Notice logs/today.log is still sent: *.log only matches at the root. Add **/*.log if you want every log gone.

How much does it save?

The build log shows the size of the context transferred to the builder:

text
 => [internal] load build context                                  4.1s
 => => transferring context: 312.45MB

After adding a .dockerignore:

text
 => [internal] load build context                                  0.1s
 => => transferring context: 186.20kB

This model adds up a typical Node.js project with and without the ignore file:

python · try it yourself
sizes_kb = {
    ".git": 48_000,
    "node_modules": 260_000,
    "dist": 4_100,
    "coverage": 2_300,
    "src": 180,
    "package.json": 2,
    "package-lock.json": 140,
    "Dockerfile": 1,
}
ignore = {".git", "node_modules", "dist", "coverage"}

def human(kb):
    return f"{kb / 1000:.1f} MB" if kb >= 1000 else f"{kb} kB"

full = sum(sizes_kb.values())
sent = sum(kb for name, kb in sizes_kb.items() if name not in ignore)
print("without .dockerignore:", human(full))
print("with .dockerignore:   ", human(sent))
print(f"{100 * (full - sent) / full:.2f}% less data to send")
without .dockerignore: 314.7 MB
with .dockerignore:    323 kB
99.90% less data to send

Tips and pitfalls

  • Ignoring node_modules matters doubly: copying a host node_modules built on macOS into a Linux image can break native modules. Let npm ci inside the image create it.
  • You may ignore the Dockerfile and .dockerignore themselves; the builder still reads them.
  • With several Dockerfiles, a file named <Dockerfile name>.dockerignore (for example api.Dockerfile.dockerignore) next to the Dockerfile takes precedence over the root .dockerignore.
  • An ignore file is not a security boundary for files you do copy. If a secret is in an included folder, it ends up in the image.

Test yourself

The .dockerignore contains *.log. Is logs/app.log sent to the builder?

  1. No, all .log files are ignored
  2. Yes, *.log only matches files at the root of the context
  3. Only if it is larger than 1 MB
  4. Docker never sends .log files

The file has .env* followed by !.env.example. What happens to .env.example?

  1. It is ignored
  2. It is included, because the last matching rule wins
  3. It causes a syntax error
  4. Both files are included

Which is NOT a benefit of a .dockerignore?

  1. Smaller build context
  2. Fewer unnecessary cache misses on COPY . .
  3. Encrypting files that are copied into the image
  4. Keeping secrets like .env out of images