Copy file

4 snippets across 3 stacks - Docker, Bash & Linux, Python

Also written as copy files

DKDocker

COPY - Copy Files into Image

DK · Dockerfile
Syntax
COPY [--chown=<user>:<group>] <src>... <dest>
Example
COPY package.json package-lock.json ./
COPY --chown=appuser:appuser . /app/

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.

Copy Files To/From a Container

DK · Debugging
Syntax
docker cp <container>:<path> <host_path>
docker cp <host_path> <container>:<path>
Example
docker cp web-api:/app/logs/error.log ./error.log
docker cp ./hotfix.js web-api:/app/hotfix.js

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.

SHBash & Linux

Copy Files & Directories

SH · Navigation & Files
Syntax
cp [options] source destination
Example
cp config.yml config.yml.bak
cp -r templates/ /opt/app/templates/
cp -i report.csv ~/Desktop/

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.

PYPython

Binary File I/O

PY · File I/O
Syntax
with open(path, 'rb') as f:
    data = f.read()
Example
# Copy a binary file
with open("image.png", "rb") as src:
    data = src.read()

with open("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.