Docker containers provide an isolated environment for running applications, but there are times when you need to transfer files between your host machine and a Docker container.
Docker simplifies this process with the docker cp
command, allowing you to copy files seamlessly. In this blog post, we'll walk through the steps to copy files from the host to a Docker container and vice versa.
Copying from Host to Container
To copy files from your host machine to a Docker container, use the following command:
$ docker cp /path/to/local/file_or_directory container_id:/path/in/container
Let's break down the components of this command:
/path/to/local/file_or_directory
: Replace this with the path to the file or directory on your host machine that you want to copy.container_id
: Replace this with the ID or name of your running Docker container./path/in/container
: Specify the path inside the container where you would like to copy the file or directory.
Example:
$ docker cp ./example.txt my_container:/app/data
This command copies the local file example.txt
to the /app/data
directory inside the my_container
container.
Copying from Container to Host
To copy files from a running container to your host machine, reverse the source and destination paths:
$ docker cp container_id:/path/in/container /path/to/local/destination
Example:
$ docker cp my_container:/app/data/example.txt ./destination_folder
This command copies the example.txt
file from the /app/data
directory inside the my_container
container to the local destination_folder
on your host machine.
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments.
Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium
Additional Tips
- Ensure that the Docker container is running when you perform the copy operation.
- If you need to copy files to or from a stopped container, consider using Docker volumes or creating a temporary container to facilitate the file transfer.
Copying files between your host machine and Docker containers is a straightforward process with the docker cp
command.
Whether you're deploying applications or managing data within containers, this method proves invaluable for seamless file transfer. Experiment with these commands and streamline your Docker workflows today!