5.1.2 Dockerignore File
A focused guide to Dockerignore File, connecting core concepts with practical Docker and container operations.
The .dockerignore file is a configuration file, conventionally placed at the root of the build context, listing patterns for files and directories that should be excluded entirely from the build context before it is ever transferred to the Docker daemon.
Basic Syntax
.dockerignore patterns closely resemble .gitignore syntax, supporting wildcards, directory exclusions, and negation.
node_modules
*.log
.git
docs/
!important.log
The final line re-includes a specific file that would otherwise have matched the earlier *.log exclusion pattern.
Why Every Project Should Have One
Without a .dockerignore, a broad COPY . . instruction (or even just the act of building) transfers every single file in the context directory, including content that has no bearing on the build and that may unnecessarily slow it down or bloat the resulting image.
.git
node_modules
__pycache__
*.pyc
.env
.vscode
README.md
A reasonably comprehensive .dockerignore like this addresses the most common sources of unnecessary build context bloat across many typical projects.
Excluding Sensitive Files for Security
Beyond pure performance, excluding files that might contain secrets or credentials prevents them from accidentally ending up baked into a built image.
.env
*.pem
secrets/
Verifying the .dockerignore Is Working as Intended
Confirming that excluded patterns are actually being honored helps catch a misconfigured or ineffective .dockerignore before it causes a problem.
docker build -t myapp . 2>&1 | grep "Sending build context"
A noticeably smaller reported context size, after adding exclusions, is a quick sanity check that the file is having its intended effect.
Why the .dockerignore File Matters
A well-maintained .dockerignore is a small, low-effort piece of configuration that directly addresses build context size, build speed, unintended file inclusion, and accidental secret leakage — making it one of the highest-value, easiest-to-adopt practices for any project using Docker.