Module 6 Lesson 3: Mastering .dockerignore
·DevOps

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.

  1. Build Speed: If you have a node_modules folder (500MB) or a data/ folder (1GB), sending that over the network to the Daemon takes time.
  2. Image Bloat: If you accidentally COPY . ., those huge folders end up inside your final image.
  3. Security (The Big One): You might accidentally copy your .env file 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?

  1. Build the image: docker build -t test-ignore .
  2. Explore it: docker run --rm -it test-ignore ls -la
  3. Check if the forbidden folders (like .git) are missing. If they are there, your .dockerignore has a typo or is in the wrong directory.

Exercise: The Context Audit

  1. Create a folder with a 10MB text file and a simple Dockerfile.
  2. Run docker build . and watch the first line of output: "Sending build context to Docker daemon...". What is the size?
  3. Add the large file to .dockerignore.
  4. Run the build again. What is the context size now?
  5. Why is it dangerous to have *.key or *.pem missing 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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn