Note COPY only handles local files from the build context. Copy dependency manifests (package.json, requirements.txt) before the rest of the source code so that dependency-install layers are cached when only your application code changes.
Note Works on both running and stopped containers. Useful for extracting crash logs or injecting a config file for debugging. Changes via cp do not persist across container recreation - use volumes for anything permanent.
Note -r is required for directories (recursive copy). -i prompts before overwriting. Without -i, cp silently overwrites the destination. Use -a to preserve permissions, timestamps, and symlinks.
# Copy a binary filewithopen("image.png","rb")as src:
data = src.read()withopen("copy.png","wb")as dst:
dst.write(data)print(f"Copied {len(data)} bytes")
Note Use 'rb' / 'wb' modes for binary files (images, archives, etc.). Never open binary files in text mode; it corrupts the data on some platforms.
Frequently asked questions
How do you copy file?
This task is covered in 3 stacks on this page: Docker, Bash & Linux, Python. The "COPY - Copy Files into Image" snippet in Docker uses `COPY [--chown=<user>:<group>] <src>... <dest>`.
Which command does the Docker example use?
The "COPY - Copy Files into Image" snippet uses `COPY [--chown=<user>:<group>] <src>... <dest>`, from the Dockerfile section of the Docker cheat sheet.
Which stacks cover "copy file" on this page?
Docker, Bash & Linux, Python. Together they hold 4 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "COPY - Copy Files into Image": COPY only handles local files from the build context. Copy dependency manifests (package.json, requirements.txt) before the rest of the source code so that dependency-install layers are cached when only your application code changes.