Using .dockerignore
What you'll learn: How to exclude unnecessary files from your Docker build context to speed up builds and shrink image sizes.
What Is a Build Context?
When you run docker build, Docker sends all files from your build directory to the Docker daemon—this is called the build context. If your project folder contains thousands of files (logs, node_modules, .git history, test data), Docker copies everything before even looking at your Dockerfile.
That's wasteful and slow.
Enter .dockerignore
The .dockerignore file works like .gitignore—it tells Docker which files and folders to exclude from the build context. Place it in the same directory as your Dockerfile.
Example .dockerignore:
node_modules
*.log
.git
README.md
tests
Now when you build, Docker skips these files entirely. Your build context shrinks from gigabytes to megabytes, uploads happen instantly, and layer caching becomes more effective.
Why This Matters
Think of .dockerignore as packing a suitcase: you don't bring your entire closet on vacation. Similarly, don't send your entire codebase to Docker when only a handful of files actually get COPY'd into the image.
Benefits:
- Faster builds – smaller context uploads in seconds instead of minutes
- Better caching – irrelevant file changes won't invalidate your cache
- Smaller images – you can't accidentally
COPYunwanted files - Security – secrets in ignored files won't leak into layers
Common Patterns
Exclude build artifacts, SCM folders, documentation, and local config:
.git
.gitignore
*.md
.env
dist
build
coverage
Key Takeaway: Use .dockerignore to exclude unnecessary files from your Docker build context—it dramatically speeds up builds, improves caching, and prevents bloat.