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:
- Faster builds: less data to transfer to the builder (think
node_modules,.git, datasets). - Better caching:
COPY . .no longer changes when an unrelated file (a log, an editor swap file) changes. - Safety: secrets such as
.envorid_rsacannot end up in an image by accident.
# .dockerignore
.git
.gitignore
node_modules
**/__pycache__
*.log
.env
.env.*
!.env.example
dist/
coverage/
Dockerfile
compose*.yamlThe 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 asnode_modulesor*.logis anchored at the root. To ignore it in every subfolder, write**/node_modulesor**/*.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.
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:
=> [internal] load build context 4.1s
=> => transferring context: 312.45MBAfter adding a .dockerignore:
=> [internal] load build context 0.1s
=> => transferring context: 186.20kBThis model adds up a typical Node.js project with and without the ignore file:
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_modulesmatters doubly: copying a hostnode_modulesbuilt on macOS into a Linux image can break native modules. Letnpm ciinside the image create it. - You may ignore the
Dockerfileand.dockerignorethemselves; the builder still reads them. - With several Dockerfiles, a file named
<Dockerfile name>.dockerignore(for exampleapi.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?
- No, all .log files are ignored
- Yes,
*.logonly matches files at the root of the context - Only if it is larger than 1 MB
- Docker never sends .log files
The file has .env* followed by !.env.example. What happens to .env.example?
- It is ignored
- It is included, because the last matching rule wins
- It causes a syntax error
- Both files are included
Which is NOT a benefit of a .dockerignore?
- Smaller build context
- Fewer unnecessary cache misses on
COPY . . - Encrypting files that are copied into the image
- Keeping secrets like
.envout of images