To copy files from a Docker container to your host machine, use the following methods:
1. Using docker cp
(Simplest Method)
Copy files or directories directly from a container to the host using the container’s ID or name.
Syntax:
docker cp <container_id>:<container_source_path> <host_destination_path>
Example:
# Copy a single file
docker cp my_container:/app/data.txt ./downloads/
# Copy an entire directory
docker cp my_container:/var/log/nginx ./nginx_logs
Notes:
- Works for stopped or running containers.
- Use
docker ps -a
to list all containers and their IDs/names.
2. Mount a Volume (Pre-Configured Access)
Mount a host directory as a volume when starting the container to automatically share files.
Example:
# Start a container with a mounted host directory
docker run -v /host/path:/container/path my_image
# Files written to `/container/path` in the container will appear in `/host/path` on the host
3. Redirect Output with docker run
For small files, redirect the output of a command to a host file.
Example:
# Save the output of a file to the host
docker run my_container cat /app/config.json > ./config.json
4. Advanced: Use tar
with docker exec
Stream files from the container to the host using tar
(useful for large directories).
Example:
# Archive and extract files from container to host
docker exec my_container tar -cf - /path/to/files | tar -xf - -C ./host_dir
Key Tips
- Permissions: Files copied to the host inherit permissions from the container (use
sudo
if needed). - Copy from Host to Container: Reverse the arguments:
docker cp ./host_file.txt my_container:/container/path/
- Wildcards: Not directly supported in
docker cp
—use shell tricks like:
docker exec my_container sh -c 'cp /app/*.log /tmp' && docker cp my_container:/tmp/ ./logs
Example Workflow
# List containers
docker ps -a
# Copy a config file from a stopped container
docker cp 5a2d3b1e:/etc/nginx/nginx.conf ./nginx.conf
# Verify the file
ls -l ./nginx.conf
Use docker cp
for quick one-off transfers, and volumes for persistent shared directories.