What is a .dockerignore file and why do you need it?
A .dockerignore lists files and folders excluded from the build context sent to the Docker daemon. It speeds up builds, keeps secrets and node_modules out of the image, and avoids needless cache invalidation.
Explain it simply
When you run docker build ., the whole folder is packed up and sent to Docker as the build context. Without filtering, that includes .git, node_modules, logs and maybe a .env file with passwords. It is like sending a courier a whole almirah when he only needs one shirt.
.dockerignore works like .gitignore: patterns for paths to leave out. Benefits: a smaller context uploads faster; COPY . . cannot accidentally copy secrets; and changes to ignored files do not invalidate the cache of a COPY . . layer. A lean context is one of the cheapest build speed-ups.
The file must sit at the root of the build context, and patterns are relative to that root.
Example
# .dockerignore
.git
node_modules
*.log
.env
Dockerfile
docker-compose.ymlWhat to say in the interview
"A .dockerignore excludes files from the build context. It makes builds faster, stops secrets like .env or heavy folders like node_modules and .git from being copied in, and prevents unnecessary cache busts on COPY . ."
Common mistakes
- Leaving .env out of .dockerignore, so credentials end up in a layer.
- Placing the file in a subfolder instead of the context root.