docker
dockerfile
containerization
file-exclusion
copy-instruction

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:

dockerfile
COPY <source> <destination>
  • 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.
dockerfile
COPY ./app /usr/src/app

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.

 
node_modules
*.log
*.tmp

Example project and patterns

Suppose your project looks like this:

 
1/project
2├── Dockerfile
3├── .dockerignore
4├── app/
5│   ├── index.js
6│   └── config.json
7├── node_modules/
8└── debug.log

These patterns control what gets excluded:

PatternEffect
/node_modulesExclude the node_modules directory
*.logExclude all files with a .log extension
**/temp/*Exclude all files in any temp directory
!.gitignoreExplicitly include .gitignore even if matched
/backup/**/*.zipExclude 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

  1. Keep the build context small: excluding files reduces the data sent to the Docker daemon.
  2. Exclude secrets: list sensitive files such as .env or secret keys. Including them in the build could expose them in the image.
  3. Rebuild without cache after big changes: when you change .dockerignore substantially, 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.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design