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/containerLet's break down the components of this command:
/path/to/local/file_or_directory: Change this with the path 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/dataThis 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/destinationExample
$ docker cp my_container:/app/data/example.txt ./destination_folderThis 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.
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.
🔍. Similar posts
How to Set Your Local Branch to Track a Remote Branch in Git
30 Sep 2025
How to Create a Git Branch From origin/master
28 Sep 2025
How to Add a Binary Folder Path to the PATH Environment Variable on macOS Using Vim
22 Jan 2025