How to Copy a File or Directory from Docker Container to Host?

Docker is a software platform that allows developers to deploy, manage, and run applications in isolated containers. Docker containers are lightweight, portable, and quickly move between different environments. One of the everyday tasks that developers may want to perform is to copy a file or directory from a Docker container to the host machine. This tutorial will discuss copying files from a Docker container to the host machine.

Copying a file from a Docker container to the host

The docker cp command can copy a file from a Docker container to the host machine. This command allows you to copy files to and from the container file system. The syntax for the command is as follows:

docker cp <containerId>:/path/to/file /host/path/target

In the above command, is the ID of the container that contains the file you want to copy. /path/to/file is the path to the file inside the container, and /host/path/target is where you want to save the file on the host machine.

For example, if you want to copy a file named codetryout.txt from a container with ID 1234567890 to the /tmp directory on the host machine, you can use the following command:

docker cp 1234567890:/path/to/codetryout.txt /tmp

Copying a directory from a Docker container to the host

Copying a directory from a Docker container to the host machine is similar to copying a file. You can copy the entire directory by copying the docker cp command. The command syntax for copying a directory is as follows:

docker cp <containerId>:/path/to/directory /host/path/target

In the above command is the container ID containing the directory you want to copy. /path/to/directory is the path to the directory inside the container, and /host/path/target is the path where you want to save the directory on the host machine.

Related tutorial: https://codetryout.com/docker-compose-copy-file-to-container/

Summary

Copying files and directories from a Docker container to the host machine is a common task for developers. The docker cp command makes copying files and directories to and from the container file system easy. In this article, we have discussed how to docker copy from container to host machine using the docker cp command.