Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 117 of 8022. Docker Image LifecycleFree lesson

Using .dockerignore to Exclude Unnecessary Files

Create effective .dockerignore files to prevent local build context bloat and ensure sensitive or irrelevant files are not copied into images.

In this lesson, you will learn how to prevent bloated image sizes and security leaks by using a .dockerignore file to keep unnecessary files out of your Docker build process.

The "Build Context" Problem

When you run docker build ., Docker sends everything in your current directory to the Docker daemon. This is known as the build context. If your folder contains a massive node_modules folder, local .git history, or secret configuration files like .env, Docker will attempt to process all of them. This makes your build slow, inflates your final image size, and risks exposing sensitive credentials that don't belong in a production container.

Creating a .dockerignore File

Just like a .gitignore file prevents unwanted files from entering your Git repository, a .dockerignore file prevents unwanted files from entering your Docker image.

Simply create a file named .dockerignore in the same directory as your Dockerfile. Inside, list the files or folders you want Docker to ignore using standard glob patterns:

# Ignore local development files
.git
.gitignore

# Ignore dependencies that should be installed inside the container, not copied
node_modules
venv

# Ignore sensitive secrets
.env
*.pem

# Ignore build artifacts
dist
build

Why This Matters

When you use a COPY . . instruction in your Dockerfile, Docker typically copies everything in the build context into your image layers. By using a .dockerignore file, you ensure that even if you use COPY . ., those sensitive or heavy files simply don't exist in the source provided to the build process. This keeps your images slim, fast to push to a registry, and secure against accidental credential leaks.

Remember: The goal is to only include the specific source code and assets required for the application to function. Anything else is just dead weight that creates "bloat" in your image layers, which we want to avoid as part of our optimization strategy.

Key Takeaway: A .dockerignore file acts as a gatekeeper, ensuring your Docker build context remains lightweight and secure by explicitly excluding irrelevant files and sensitive data before they are ever processed into your image layers.