How to Copy Files Between Host and Container
Copying files between your host and a Docker container is a common task: exporting logs, backing up data, or injecting configs.
The docker cp command is the simplest and safest way to do this.
This guide shows how to copy files and directories both ways, and how to fix common permission issues.
The docker cp command
docker cp works like Unix cp, but one side of the path references a container:
docker cp CONTAINER:SRC_PATH DEST_PATH
docker cp SRC_PATH CONTAINER:DEST_PATH
CONTAINERcan be a name or ID- Containers can be running or stopped
Copy from container to host
docker cp my-container:/etc/nginx/nginx.conf ./nginx.conf
Steps:
-
Find the container name:
docker ps -a -
Copy the file or directory.
This is commonly used to:
- extract logs
- back up configs
- inspect generated files
Copy from host to container
docker cp ./nginx.conf my-container:/etc/nginx/nginx.conf
Restart the container if needed:
docker restart my-container
Copying directories
Directories are copied recursively by default.
From container to host:
docker cp my-app:/var/log/app ./logs
From host to container:
docker cp ./src my-app:/app/src
Common issues and fixes
Permission problems
Files may end up owned by root inside the container.
Check ownership:
docker exec -it my-container ls -l /path
Fix ownership:
docker exec -u 0 my-container chown appuser:appgroup /path
Path not found
- Always use absolute paths inside containers
- Relative paths depend on the container’s working directory
Container not found
docker cp works on stopped containers too.
Verify with:
docker ps -a
When NOT to use docker cp
For ongoing development or frequent file changes, docker cp is the wrong tool.
Use bind mounts or volumes instead.
Example with Docker Compose:
services:
web:
image: nginx
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
Changes on the host are instantly visible in the container.
Key takeaways
docker cpcopies files between host and container safely- Works with running or stopped containers
- Directories are copied recursively
- Permission issues are common but fixable
- For development, prefer bind mounts or volumes
Deploy without manual copying
On Hostim.dev, you define volumes once in docker-compose.yml and get persistent storage without manual file copying.