Copying Files to and from Docker Containers
While working on a Docker project, you might require copying files to and from Docker Containers and your Local Machine. Once you have built the Docker Image with a particular Docker build context, building it again and again just to add small files or folders inside the Container might be expensive because usually, Docker Images are of very large sizes.
Docker provides us with very helpful copy commands which allow us to seamless copy files to and from Docker Containers and Local Systems. In this article, we will discuss how to use the Docker cp commands using practical examples.
Copying files from Docker Container to Local Machine
Follow the below steps to copy a file from a docker container to a local machine:
Step 1: Create a Docker Container.
sudo docker run -it --name my-container ubuntu
Step 2: Create a File inside Container
echo "geeksforgeeks" > geeksforgeeks.txt
Step 3: Get the Container ID
sudo docker start my-container sudo docker container ls
Step 4: Copy the file to your Local System
You can use the docker cp command to copy the file.
sudo docker cp 135950565ad8:/geeksforgeeks.txt ~/Desktop/geeksforgeeks.txt
The first path (Source) is the path in the Docker Container and the second one is the path inside your Local System (Destination).
Copying files from Local System to Docker Container
Follow the below steps to copy files from a local machine to the Docker container:
Step 1: Create a file on your local machine
Step 2: Copy the File to the Container
You can use cp instruction. The path on the left should be on the local machine (Source) and on the right should be of Docker Container (Destination).
sudo docker cp ~/Desktop/to-be-copied.txt 135950565ad8:/to-be-copied.txt
Step 3: Verify the copied file
To start the Container, use the following command.
sudo docker exec -it my-container /bin/bash