Difficulty: Beginner
How do you copy files between the host and a container, and what are the limitations of docker cp?
Use docker cp <host_path> <container>:<container_path> to copy into a container, and docker cp <container>:<container_path> <host_path> to copy out. It works on running and stopped containers, copies directories recursively, and does not need any tools inside the image. It is meant for debugging and one-off tasks: anything you copy into a container is lost when that container is recreated.
docker cp ./config.yml web:/etc/app/config.ymldocker cp web:/var/log/app/error.log ./error.log/. matters: docker cp ./site/. web:/usr/share/nginx/html copies the contents of site, while ./site copies the folder itself into the target.- as the source or destination to stream a tar archive through stdin or stdout, for example to pipe logs into tar on the host.Behind the scenes Docker builds a tar stream of the source and extracts it at the destination, which is why no cp or tar binary is needed in the image, and why it even works on distroless images.
docker exec -u 0 web chown ....docker cp.-a / --archive preserves the original UID and GID from the source./proc, /sys and /dev, or tmpfs mounts.docker compose up that recreates it.Good uses: pulling a heap dump, core file or log out of a crashed container; dropping a test config into a dev container; extracting a build artefact from a container (though BuildKit's docker build --output type=local,dest=./out . is cleaner for build outputs).
For files that should change while the container runs, such as source code during development, use a bind mount (or Compose's develop.watch). For configuration in production, bake it into the image or provide it through volumes, config files mounted read-only, or environment variables.
# Into a running container
docker cp ./nginx.conf web:/etc/nginx/nginx.conf
docker exec web nginx -s reload
# Contents of a folder (note the trailing /.)
docker cp ./site/. web:/usr/share/nginx/html
# Out of a stopped or crashed container
docker cp payments-api:/tmp/heapdump.hprof ./heapdump.hprof
# Preserve original UID/GID
docker cp -a ./data/. web:/srv/data
Direction is set by which side has the container: prefix; /. copies a folder's contents rather than the folder.
docker cp ./uploads/. app:/home/node/uploads
# Files arrive owned by root; give them to the app user
docker exec -u 0 app chown -R node:node /home/node/uploads
Copied files are root-owned by default, so a non-root app user needs a chown before it can write to them.
docker cp, Container filesystem, File ownership, Tar streaming