Docker COPY with exclusions using .dockerignore
Codemia Knowledge Hub ·
To exclude files from a COPY, list them in a .dockerignore file at the root of the build context. Anything matched there is left out of the build context, so COPY cannot copy it into the image.
How COPY works
COPY takes a source and a destination and copies files from the host into the image:
- Source: a single file, multiple files, or directories. Patterns and wildcards are supported.
- Destination: the path inside the image's file system where the content goes.
This copies everything in the local app directory into /usr/src/app in the image.
Excluding files with .dockerignore
.dockerignore works much like .gitignore: any file or directory it lists is excluded when you copy with COPY.
Example project and patterns
Suppose your project looks like this:
These patterns control what gets excluded:
| Pattern | Effect |
/node_modules | Exclude the node_modules directory |
*.log | Exclude all files with a .log extension |
**/temp/* | Exclude all files in any temp directory |
!.gitignore | Explicitly include .gitignore even if matched |
/backup/**/*.zip | Exclude all .zip files within /backup |
Why the build context matters
The build context is the directory tree available to the build. Every file in it can be sent to the Docker daemon unless .dockerignore excludes it, so a smaller context means a faster, more efficient build.
Tips for .dockerignore
- Keep the build context small: excluding files reduces the data sent to the Docker daemon.
- Exclude secrets: list sensitive files such as
.envor secret keys. Including them in the build could expose them in the image. - Rebuild without cache after big changes: when you change
.dockerignoresubstantially, consider rebuilding without cache so unwanted files do not linger in earlier layers.
Combined with a well-written .dockerignore, COPY gives you precise control over what ends up in the image, which makes images smaller and more secure.
Related reading
- COPYing a file in a Dockerfile, no such file or directory?
- Copying files from Docker container to host
- Copying files to a container with Docker Compose
- core_dns stuck in ContainerCreating status
- Correct way to detach from a container without stopping it
- Couldn't connect to Docker daemon on Mac OS X
- Create kubernetes docker-registry secret from yaml file?
- Create kubernetes pod with volume using kubectl run
System design interview problems on this topic
- Design a Container Orchestration System: solution and walkthrough
- Design a Code Deployment System: solution and walkthrough
- Design GitHub Actions: solution and walkthrough
- Design a Serverless Architecture Framework: solution and walkthrough

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseSystem Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.