What is .dockerignore and why use it?
· Category: Docker
Short answer
.dockerignore is a text file that tells Docker which files and directories to exclude from the build context. It reduces build time, shrinks images, and prevents secrets from being accidentally baked into images.
How it works
When you run docker build, the Docker client sends the entire build context to the daemon. .dockerignore filters this context, so excluded files are never sent and never participate in layer caching.
Example
node_modules
.git
.env
*.md
dist
.vscode
Why it matters
A large build context slows down builds and can invalidate layers unnecessarily. Including .env or private keys in the context is a serious security risk even if they are not explicitly copied, because they are available during the build.
Tips
- Ignore dependency directories and editor files.
- Ignore test files and documentation if they are not needed in the image.
- Use
.dockerignorealongside.gitignorebut tailor them separately.
Common issues
.dockerignorepatterns follow similar rules to.gitignorebut are not identical.- Negation patterns like
!important.envcan be tricky. - Changes to
.dockerignoreitself do not invalidate the cache, but they affect the next build.