Q: How do you copy a file from a container to the host?
docker cp <container>:/path/to/file /host/path.
Want to master this scenario in a live sandbox? KodeKloud's Docker Certified Associate (DCA) Hands-On Lab Course covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: To <strong>copy a file from a container to the host</strong>, use <code>docker cp <container>:/path/in/container /path/on/host</code>. It works on running and stopped containers and does not need a shell or <code>tar</code> in the image. Interviewers ask it because it is an everyday debugging task with several traps: ownership, symlinks, mounted paths and the fact that you can pull files from a crashed container for forensics. A thorough answer lists alternatives such as bind mounts, streaming <code>tar</code> and BuildKit <code>--output</code> for build artifacts.
Mental model: docker cp talks to the daemon
Unlike exec cat, docker cp reads the container filesystem through the Docker API, so the container does not have to run or contain any tools. Choose the method by whether the container is running, how big the data is, and whether the task will repeat.
- Direction: either way works.
docker cp c:/src destcopies out, anddocker cp src c:/destcopies in. - Stopped containers: the writable layer persists until removal, so you can recover logs and dumps from an exited container.
- Directories: they copy recursively. A trailing
/.on the source copies the contents rather than the directory itself. - No shell required: works with distroless and scratch images, where
execcannot help. - Path rules: the container path is always absolute inside the container filesystem, and relative host paths resolve against your current directory, so check
pwdbefore copying large trees.
Hands-on: copy a file from a container to the host
Basic forms and the flags that matter.
docker cp my-app:/var/log/app/error.log ./error.log
docker cp my-app:/etc/nginx/. ./nginx-conf/ # contents only
docker cp -a my-app:/data ./data-backup # keep UID/GID
# Works on a stopped container too
docker ps -a --filter name=my-app
docker cp my-app:/tmp/core.1234 ./core.1234
- Single file: copy to the current directory with
.. - Directory contents: use
/.to avoid nesting an extra folder. - Preserve ownership:
-a(archive) copies UID/GID information. By default files on the host end up owned by the invoking user. - Follow symlinks:
-Lfollows a symlink in the source path instead of copying the link. - Overwrite behaviour: copying onto an existing host file replaces it without prompting. Copy into a new directory when you are collecting evidence to avoid clobbering earlier captures.
Alternatives when cp is not enough
Pick the method that fits automation, large trees or build artifacts.
# Stream a directory with compression
docker exec my-app tar -C /data -czf - . > data.tgz
# Export build output directly to the host (BuildKit)
docker build --target artifacts --output type=local,dest=./out .
ls ./out
- Stream with tar:
docker exec my-app tar -C /data -cf - . | tar -xf - -C ./outhandles many files and lets you compress. It needstarin the image. - Pipe a single file:
docker exec my-app cat /etc/hosts > hosts.txtis simple but requires a running container and acatbinary. - Bind mount up front: if you know you will need the output, mount a host directory so files appear without copying.
- Build artifacts: with BuildKit,
docker build --output type=local,dest=./out .exports files from a build stage (for example aFROM scratchstage) with no container to manage. - Compose services:
docker compose cp web:/app/out.txt ./out.txtaddresses the service by name, which is convenient when container names include project prefixes.
Verify the copy and avoid pitfalls
A successful exit code does not guarantee you copied the right thing. Check each symptom against the evidence before changing anything.
- Check integrity: compare
sha256sumof the host file withdocker exec my-app sha256sum /pathwhen it matters. - Special mounts: files under tmpfs mounts and under
/procor/syscannot be copied withdocker cp. Read them withexec. - Permissions: unreadable output often means root ownership with
-a. Fix withsudo chown. - Large or sensitive files: copying core dumps or database files can expose secrets. Store them with restricted permissions and delete after use.
- Size awareness: copying a multi-gigabyte directory goes through the daemon and can fill the host disk. Check
docker exec my-app du -sh /pathfirst.
Production practice: avoid manual copies
Repeated copying is a sign that output should go somewhere durable.
- Ship logs and dumps out: write logs to stdout and use a log driver or agent. Mount a volume for heap dumps.
- Kubernetes:
kubectl cp ns/pod:/path ./pathrequirestarin the container.kubectl execwithcator ephemeral containers works otherwise. - CI artifacts: use BuildKit
--outputor your CI artifact upload rather thandocker cpfrom a leftover container. - Remote daemons: with a remote Docker context the file lands on your local machine, not the remote host, which is useful for pulling diagnostics but slow over poor links.
- I use <code>docker cp container:/path ./dest</code>, which reads through the daemon so it works on stopped containers and shell-less images.
- I verify with a checksum and use <code>-a</code> when ownership matters, or tar streaming for large trees.
- For repeat needs I mount volumes or use BuildKit <code>--output</code> instead of manual copying.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Removing a crashed container before copying its files The writable layer disappears with the container. Copy logs and dumps first.
- Expecting docker cp to read tmpfs or /proc It does not support those mounts, so you get errors or empty results. Use exec to read them.
- Forgetting the trailing /. on directories Without it you copy the directory itself, creating an unexpected nested folder.
- Using exec cat on binary files via a TTY Allocating a TTY (-t) can corrupt binary output. Use docker cp or no -t.