How to Use docker cp: Copy Files Between Host and Containers
Use
docker cp to copy files or folders between your host and a Docker container. The command syntax is docker cp [OPTIONS] SOURCE_PATH CONTAINER:DEST_PATH to copy from host to container, or docker cp [OPTIONS] CONTAINER:SOURCE_PATH DEST_PATH to copy from container to host.Syntax
The docker cp command copies files or directories between the host and a container.
Syntax parts explained:
docker cp: The command itself.SOURCE_PATH: Path of the file or folder to copy. Can be on host or inside container.CONTAINER: The container name or ID.DEST_PATH: Destination path where the file/folder will be copied.OPTIONS: Optional flags (rarely needed).
bash
docker cp [OPTIONS] SOURCE_PATH CONTAINER:DEST_PATH docker cp [OPTIONS] CONTAINER:SOURCE_PATH DEST_PATH
Example
This example copies a file named example.txt from the host to the container mycontainer at path /tmp/. Then it copies a file /var/log/app.log from the container back to the host.
bash
docker cp example.txt mycontainer:/tmp/ docker cp mycontainer:/var/log/app.log ./app.log
Common Pitfalls
Common mistakes when using docker cp include:
- Using container names or IDs incorrectly. Always verify the container is running or exists.
- Forgetting the colon
:between container name and path. - Trying to copy files from a stopped container (it won't work).
- Not having correct permissions on the host or container paths.
Example of a wrong command and the correct form:
bash
docker cp mycontainer/tmp/example.txt ./ # Wrong: missing colon docker cp mycontainer:/tmp/example.txt ./ # Correct
Quick Reference
| Command | Description |
|---|---|
| docker cp SOURCE_PATH CONTAINER:DEST_PATH | Copy file/folder from host to container |
| docker cp CONTAINER:SOURCE_PATH DEST_PATH | Copy file/folder from container to host |
| docker cp -L ... | Follow symbolic links (rarely used) |
| docker cp --help | Show help and options |
Key Takeaways
Use docker cp to transfer files between host and container easily.
Always include a colon ':' after the container name to specify container paths.
Verify container is running or exists before copying files.
Check file permissions to avoid access errors.
Use docker cp with correct source and destination order depending on copy direction.