Docker

How do I Copy a Directory From Container to Host?

In a Docker container, a directory is a folder that stores subfolders and files related to the container’s functionality. Sometimes, users may want to copy a particular directory or files from the Docker container to the host machine for different purposes, such as sharing the directory with other team members or for debugging. For such a corresponding purpose, Docker allows users to copy any directory or file from the container to the local host machine.

This write-up will explain the method to copy a directory from the Docker container to the local host machine.

How to Copy the Directory From the Container to Local Host?

To copy the directory from the Docker container to the host, check out the following steps:

  • Display all containers.
  • Choose the particular container.
  • Copy the desired directory from the container to the host using the “docker cp <container-name/id>:<directory-path> <host-path>” command.
  • Verification.

Step 1: View all Existing Containers

First, list all the existing containers and choose the desired container to copy its directory:

docker ps -a

The below output displays two containers. We have selected the “cont1” container:

Step 2: Copy Directory from Container to Host

To copy a directory from container to host, utilize the “docker cp <container-name/id>:<directory-path> <host-path>” command:

docker cp cont1:/usr/share/nginx/html C:\Docker\Data

Here:

  • cont1” is the container name.
  • /usr/share/nginx/html” is the directory’s path.
  • C:\Docker\Data” is the path of the directory on the host machine.

The above-listed command will copy the “html” directory from the container and save it to the host machine:

Step 3: Verification

For the verification, first, navigate to the host directory to ensure that the desired directory has been copied into it:

cd C:\Docker\Data

Then, list the host directory content using the provided command:

ls

The below output indicates that the “html” directory has been copied successfully:

We have explained the easiest way to copy a directory from the container to the host machine.

Conclusion

To copy a particular directory from the container to the host machine, first, choose the desired container to copy its directory. Then, execute the “docker cp <container-name/id>:<directory-path> <host-path>” command to copy the desired directory from the container and save it to the host machine. Next, redirect to the host directory and view its content for verification. This write-up explained the method to copy a directory from the Docker container to the local host machine.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.