The COPY instruction in a Dockerfile copies new files or directories from the build context and adds them to the filesystem of the container image.
The COPY instruction is a fundamental command used to transfer files and directories from your host machine (specifically the build context) into the image being built. It creates a new layer in the image containing the copied files, which become part of the final image. This is essential for including application source code, configuration files, scripts, and any other assets needed at runtime. The instruction copies files exactly as they are, preserving permissions and metadata where possible, without any additional processing.
The basic syntax is COPY [--chown=<user>:<group>] <src>... <dest>. The source path(s) are relative to the build context (the directory where you run docker build), and the destination path is absolute within the container or relative to the WORKDIR. COPY automatically creates missing directories in the destination path and supports wildcards in source file specifications using Go's filepath.Match rules .
COPY only copies files that exist in the build context—it cannot access files outside the context directory (like ../file.txt) for security reasons .
Each COPY instruction creates a new layer, so grouping related files together reduces image size and layer count .
The --chown flag changes file ownership, useful when running containers with non-root users .
COPY respects the .dockerignore file, which can exclude unnecessary files from being sent to the Docker daemon .
Unlike ADD, COPY does not automatically unpack archives or download URLs, making it more predictable and recommended for most use cases .