Docker .dockerignore and .gitignore Setup

Configure .gitignore and .dockerignore for Docker projects. Covers Docker build context optimization, multi-stage builds, and Compose local overrides.

DevOps

Detailed Explanation

Docker projects need two ignore files: .gitignore for version control and .dockerignore for build context. They serve different purposes but often overlap significantly.

Docker-specific .gitignore patterns:

docker-compose.override.yml
.docker/
*.tar
*.gz
  • docker-compose.override.yml — Local overrides for Docker Compose (e.g., mounting source code, exposing debug ports). Each developer may have different overrides. The base docker-compose.yml is committed.
  • Container data volumes — Directories mounted as volumes for local development (e.g., postgres-data/, redis-data/).
  • .docker/ — Some teams store local Docker configurations here.

The .dockerignore file (build context):

When you run docker build, Docker sends the entire build context (current directory) to the daemon. Without a .dockerignore, this includes node_modules/, .git/, and test files — making builds slow and images bloated.

Essential .dockerignore patterns:

.git
node_modules
npm-debug.log
.env*
Dockerfile
docker-compose*.yml
.dockerignore
README.md
.github
coverage
.vscode
.idea

Key differences from .gitignore:

  1. .dockerignore should include .git/ — Docker does not need your git history, and excluding it can save hundreds of megabytes from the build context.
  2. .dockerignore should include node_modules/ even if you install dependencies inside the Dockerfile — sending existing modules to the daemon wastes time and can cause platform mismatch issues.
  3. Dockerfile itself should be in .dockerignore — the build process reads it separately and does not need it in the context.

Multi-stage build tip: Even with a good .dockerignore, use multi-stage builds to keep final images small. Install dependencies and build in a builder stage, then copy only the production output to a minimal runtime image.

Security: Never include .env files in Docker build context. Pass secrets via build arguments, Docker secrets, or runtime environment variables. Secrets in build args still appear in image layer history, so prefer runtime injection for truly sensitive values.

Use Case

A DevOps engineer notices Docker builds taking 5 minutes because the entire .git directory and node_modules are being sent as build context to the Docker daemon.

Try It — .gitignore Generator

Open full tool