4.2.3.1 COPY App Files
A focused guide to COPY App Files, connecting core concepts with practical Docker and container operations.
Using COPY for application files brings an application's actual source code into the image, typically as one of the later instructions in a Dockerfile, positioned deliberately after dependency installation so that source code changes do not invalidate the more expensive dependency installation layer's cache.
Copying Application Source
The most common use of COPY brings the entirety of an application's source code into the image, usually after dependencies have already been installed in earlier layers.
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "server.js"]
The final COPY . . brings in the full application source, positioned after dependency installation specifically to preserve caching for that more time-consuming step.
Selectively Copying Only What's Needed
Rather than copying an entire repository indiscriminately, copying only the specific directories an image actually needs keeps the image free of unrelated files that might exist elsewhere in the repository.
COPY src/ ./src/
COPY config/ ./config/
This is particularly relevant in monorepos, where a single repository might contain code for several unrelated services, only one of which is relevant to a given image.
Using .dockerignore to Exclude Unwanted Files
Even with a broad COPY . ., a .dockerignore file can exclude specific files and directories that should never end up in the image, regardless of how broadly the COPY instruction itself is written.
node_modules
.git
*.log
.env
Verifying What Was Actually Copied
After a build, the application files actually present inside the resulting image can be inspected directly, confirming the COPY instructions produced exactly the intended result.
docker run --rm myapp:1.0 find /app -type f
Why Copying Application Files Correctly Matters
Getting the COPY instructions for application files right — what to include, what to exclude, and where to position them relative to dependency installation — has a direct and significant impact on both build speed (through caching) and the correctness of the resulting image's contents.