Dockerfile by Example: File Copy Patterns
COPY and ADD are used to move files into the image. This sample code explains the differences and shows how to use .dockerignore to exclude unwanted files.
Code
FROM python:3.9-slim
WORKDIR /app
# 1. Copy specific files
COPY requirements.txt .
# 2. Copy a directory
# Copies contents of 'src' on host to '/app/src' in container
COPY src/ ./src/
# 3. Copy with ownership change (useful for non-root users)
RUN useradd -m myuser
USER myuser
COPY --chown=myuser:myuser . .
# 4. ADD has extra features (URL download, auto-extraction)
# Generally prefer COPY unless you need these specific features
ADD https://example.com/data.json ./data/
ADD archive.tar.gz ./extracted/Explanation
The COPY instruction is the standard and preferred method for adding files from the local build context to the container. It performs a simple, transparent file copy. In contrast, ADD is a more complex instruction that includes additional features: it can download files from remote URLs and automatically extract local tar archives (gzip, bzip2, etc.) into the destination directory. Because of this implicit behavior, COPY is recommended for predictability and security unless the specific features of ADD are required.
File copying mechanisms and best practices:
COPYsupports basic file and directory replication from build contextADDsupports remote URL fetching and archive extraction.dockerignoreexcludes files from the build context (like.git,node_modules)--chownflag sets ownership during copy, avoiding extra layers
The .dockerignore file is crucial for optimizing builds. It functions like .gitignore, preventing unnecessary or sensitive files (such as local secrets, logs, or massive dependency folders) from being sent to the Docker daemon. This reduces the build context size, speeds up the build process, and enhances security by ensuring only intended artifacts are included in the image.
Code Breakdown
COPY src/ ./src/ copies directory contents. Destination must be explicit.COPY --chown=... sets permissions atomically, preventing layer bloat.ADD archive.tar.gz ... automatically unpacks the archive to destination.ADD https://... downloads file from URL. Not recommended if authentication is needed.
