When building Docker images, the COPY instruction in a Dockerfile is one of the most commonly used commands. It allows you to copy files and directories from your local machine into the Docker image during the build process. However, in many cases, you don’t want to copy everything—especially temporary files, large development folders, or sensitive files. This is where exclusions come in handy.
In this blog, we’ll explore how to effectively use COPY with file exclusions when building Docker images.
✅ Why Exclude Files When Using COPY?
- Prevent unnecessary files (e.g.,
.git, node_modules, logs) from bloating the image size. - Avoid copying sensitive data like credentials or configuration files used only in development.
- Improve build speed by copying only what’s required.
- Maintain a clean, production-ready image.
✅ The Challenge: COPY Doesn’t Support Exclusion by Default
The basic syntax of COPY is simple:
COPY <source> <destination>
But unfortunately, the COPY command does not natively support exclusion patterns like .dockerignore in the command itself.
✅ The Solution: Use .dockerignore File
Docker provides a .dockerignore file that works similarly to .gitignore. It tells Docker which files and directories to ignore during build context upload. This keeps unwanted files from being sent to the Docker daemon and prevents them from being copied into the image.
Example .dockerignore
# Ignore node_modules directory
node_modules
# Ignore Git files
.git
.gitignore
# Ignore logs and temp files
*.log
tmp/
# Ignore environment files
.env
When using COPY . /app in the Dockerfile, Docker will copy everything from the build context to /app, except the files listed in .dockerignore.
✅ Sample Dockerfile Setup
Dockerfile
FROM node:16-alpine
WORKDIR /app
# Copy all necessary files, excluding ignored files
COPY . /app
RUN npm install
CMD ["node", "index.js"]
.dockerignore
node_modules
.git
*.log
.env
✅ Why Use .dockerignore Over Manual COPY?
- Simple and declarative way to manage exclusions.
- No need to explicitly specify individual files in the Dockerfile.
- Helps prevent accidentally copying sensitive files.
- Makes builds faster by sending less data to Docker daemon.
✅ Advanced Tip: Selective COPY with Specific Patterns
If you want fine-grained control, instead of copying everything, you can use multiple explicit COPY commands:
COPY package.json /app/
COPY src/ /app/src/
This way, you control exactly what gets copied, but managing .dockerignore is easier for general exclusion needs.
✅ Conclusion
The best way to manage exclusions when using COPY in Docker is through a well-configured .dockerignore file.
It keeps your image lean, secure, and faster to build. Rather than trying to add exclusions directly into the COPY command (which isn’t supported), rely on .dockerignore for clean and efficient Docker image builds.