Module 6 Lesson 3: Mastering .dockerignore
Protect your secrets and speed up your builds. Learn how to use .dockerignore to keep sensitive and unnecessary files out of your Docker images.
Module 6 Lesson 3: Mastering .dockerignore
A .dockerignore file is just as important as your Dockerfile. It tells the Docker CLI which files and folders to exclude when sending your code to the Docker Daemon for a build.
1. Why do we need it?
When you run docker build ., the . (the context) tells Docker to bundle EVERYTHING in that folder and send it to the Daemon.
- Build Speed: If you have a
node_modulesfolder (500MB) or adata/folder (1GB), sending that over the network to the Daemon takes time. - Image Bloat: If you accidentally
COPY . ., those huge folders end up inside your final image. - Security (The Big One): You might accidentally copy your
.envfile containing database passwords or your.ssh/folder into a public image.
2. Common Patterns
Create a file named .dockerignore in your project root:
# Exclude git history
.git
.gitignore
# Exclude local dependencies
node_modules
venv
.env
# Exclude build artifacts
dist
build
*.log
# Exclude OS-specific junk
.DS_Store
Thumbs.db
3. The "Allow List" Strategy
Sometimes it's safer to ignore everything and only "Allow" specific files. You do this with the * (ignore all) and ! (exception) syntax.
# 1. Ignore EVERYTHING
*
# 2. Allow only the things we need
!src/
!package.json
!Dockerfile
4. Testing your .dockerignore
How do you know it's working?
- Build the image:
docker build -t test-ignore . - Explore it:
docker run --rm -it test-ignore ls -la - Check if the forbidden folders (like
.git) are missing. If they are there, your.dockerignorehas a typo or is in the wrong directory.
Exercise: The Context Audit
- Create a folder with a 10MB text file and a simple Dockerfile.
- Run
docker build .and watch the first line of output:"Sending build context to Docker daemon...". What is the size? - Add the large file to
.dockerignore. - Run the build again. What is the context size now?
- Why is it dangerous to have
*.keyor*.pemmissing from your.dockerignore?
Summary
The .dockerignore file is your first line of defense. It keeps your images lean, your builds fast, and your credentials private. Never start a project without one!
Next Lesson: Automated health checks: Healthchecks in Dockerfiles.