.dockerignore — Keeping Your Build Context Fast and Safe
What Is .dockerignore in Simple Terms?
When you run docker build ., Docker sends your entire project directory to the Docker daemon before executing a single Dockerfile instruction. Without .dockerignore, that includes your 500MB node_modules folder, your .git history, your .env secrets file, and every test fixture and build artifact you have ever created. All of it gets sent over the network before the build even starts.
.dockerignore tells Docker which files to exclude. It uses the same syntax as .gitignore.
Without .dockerignore: Sending build context to Docker daemon 890.5MB (890MB sent before build starts) With .dockerignore: Sending build context to Docker daemon 2.3MB (386x reduction — build starts immediately)Production .dockerignore Template
# .dockerignore # Dependencies — always install inside container, never copy from hostnode_modules/npm-debug.log.npm/.yarn/__pycache__/*.pycvenv/.venv/ # Build output — built inside container via multi-stagedist/build/.next/out/target/ # Version control.git/.gitignore.gitattributes # Environment and secrets — NEVER in images.env.env.*!.env.example*.pem*.key*.crt # Development tools.vscode/.idea/*.swp*.swo # Testscoverage/.nyc_output/__tests__/*.test.ts*.spec.ts*.test.js*.spec.js # Docker files themselvesDockerfileDockerfile.*docker-compose.ymldocker-compose.*.yml # Documentationdocs/*.md!README.md # macOS.DS_Store # Logs*.loglogs/Measuring the Impact
# Check build context size before adding .dockerignoredocker build .# Sending build context to Docker daemon 890.5MB # Add .dockerignore, rebuilddocker build .# Sending build context to Docker daemon 2.3MB # 386x reduction — instant improvement with zero other changesImportant Distinction
.dockerignore controls what is SENT TO THE DAEMONDockerfile COPY controls what goes INTO THE IMAGE You need both: .dockerignore: excludes node_modules from context (build speed) COPY src/ /app/src/: copies only src, not everything (image cleanliness) If a file is in .dockerignore: It is NOT sent to daemon COPY instructions cannot access it It cannot end up in the imagePLACEMENT PRO TIP**Tip:** Create `.dockerignore` as the very first file in every new project — before writing any Dockerfile. It is much easier to add it at the start than to discover 6 months later that your API keys are in every image you have ever pushed to your registry.
COMMON MISTAKE / WARNING**Common Mistake:** Not adding `.env` to `.dockerignore`. Your `.env` file contains real credentials. If it gets sent to the daemon and a `COPY . .` instruction runs, it ends up baked into an image layer permanently — visible to anyone who runs `docker history` on the image.