Copy Files from Docker Container to Local Machine

DockerOperating SystemOpen Source

If you are working on a project that requires frequent copying of files and folders either from container to your local machine or from the local machine to the container, docker provides an easy and simple way to do that. If you have already built a docker image which is of large size and contains a large number of files and in the midst of the project you want to copy files to and from the container, it’s highly inefficient to put the files in the docker build context and build images repeatedly. Instead, docker allows easy copying of files to and from containers.

In this article, we will learn about the commands that will allow us to do so. We will look for commands for copying the files from both local machine to container and vice versa.

To copy a file from container to local machine.

If you want to copy a file from your container to your local machine, you can use the following command.

sudo docker cp <Container ID>:<Path of file inside the container> <Path in the local machine>

For example,

If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /usr/src/app/file.txt in the container to /home/username/Desktop/folder in the local machine, you can use the command -

sudo docker cp f4628571q5gc:/usr/src/app/file.txt home/username/Desktop/folder/

If you want to paste the file in the current directory of you local machine, you can simply use -

sudo docker cp f4628571q5gc:/usr/src/app/file.txt . (Don’t forget the dot)

If you want to copy all the files from a particular folder in container, to a folder in the local machine, use the following command -

sudo docker cp f4628571q5gc:/usr/src/app/ home/username/Desktop/folder/

To copy a file from local machine to container

If you want to copy a file from your local machine to a container, you can use the following command.

sudo docker cp <Path in the local machine> <Container ID>:<Path of file inside the container>

For example,

If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /home/username/Desktop/folder/file.txt in the local machine to /usr/src/app/ in the container, you can use the command -

sudo docker cp /home/username/Desktop/folder/file.txt f4628571q5gc:/usr/src/app/

If you want to copy all the files from a folder in your local machine to a folder in the container, use the following command -

sudo docker cp /home/username/Desktop/folder f4628571q5gc:/usr/src/app/

To conclude, after you have already built an image with a build context and you want to copy files and folders to and from the container, you can easily do that using the commands mentioned above.

raja
Published on 01-Oct-2020 19:45:06
Advertisements