A .dockerignore file specifies which files and directories to exclude from the Docker build context, improving build performance, security, and image size.
The .dockerignore file is a configuration file used by Docker to intentionally exclude certain files and directories from being sent to the Docker daemon as part of the build context. It works similarly to .gitignore, following pattern-based exclusion rules. When you run docker build, Docker packages the entire build context directory (typically the current directory) and sends it to the Docker daemon. Without .dockerignore, this can include unnecessary files like local dependencies, logs, or source control metadata, causing bloated images and slower builds.
Performance: Reduces build context size, making the initial context upload to the Docker daemon faster .
Security: Prevents sensitive files like .env, private keys, or credentials from being included in the build context and potentially ending up in the final image .
Image size: Excluding unnecessary files prevents them from accidentally being copied into the image, keeping images lean and efficient .
Build reliability: Avoids conflicts where local development files could override expected files in the image .
Cache efficiency: Smaller context means Docker's build cache works more effectively, reducing unnecessary rebuilds .
The file uses pattern matching similar to .gitignore. Patterns like node_modules/ exclude entire directories, *.log excludes all files with that extension, and !important.log can be used as an exception to re-include files that would otherwise be excluded. The Docker CLI processes the build context by loading the entire directory, then applying the .dockerignore rules to remove matched files. This happens client-side before sending the context to the daemon, making .dockerignore essential for both security and performance.