Docker cp command
docker cpThe command is used to copy files or directories between Docker containers and the host machine.
docker cpThe command supports file copy operations from the container to the host machine, or from the host machine to the container.
Syntax
docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
SRC_PATHSource path (can be a path inside the container or on the host machine).CONTAINER: The name or ID of the container.DEST_PATHDestination path (can be a path inside the container or on the host machine).
Copy file from container to host
docker cp my_container:/path/in/container /path/on/host
Copy the /path/in/container file or directory inside container my_container to /path/on/host on the host machine.
Copy file from host to container
docker cp /path/on/host my_container:/path/in/container
Copy the /path/on/host file or directory on the host machine to /path/in/container inside container my_container.
Copy directory from container to host
docker cp my_container:/path/in/container /path/on/host
Copy the /path/in/container directory and its contents inside the container to /path/on/host on the host machine.
Copy directory from host to container
docker cp /path/on/host my_container:/path/in/container
Copy the /path/on/host directory and its contents on the host machine to /path/in/container inside container my_container.
Example
Container copy file to host
Start a container and create a file:
docker run -d --name my_container ubuntu bash -c "echo 'Hello, Docker!' > /hello.txt"
Copy file from container to host:
docker cp my_container:/hello.txt ./hello.txt
Copy the /hello.txt file inside the container to the current host machine directory.
View the copied file content:
cat hello.txt
Output:
Hello, Docker!
Copy file from host to container
Copy a file to container:
docker cp ./hello.txt my_container:/hello.txt
Copy the hello.txt file on the host machine to /hello.txt inside the container.
Enter the container to view the file contents:
docker exec -it my_container cat /hello.txt
Output:
Hello, Docker!
Notes
docker cpThe command does not modify the source file or directory; it only performs a copy operation.- The destination path must be a valid path, and there should be sufficient permissions on the host machine or in the container to perform the write operation.
- When handling large files or directories, the copy operation may take some time.
docker cpThe command is a useful tool provided by Docker for copying files or directories between containers and the host machine. This command is suitable for operations such as backup, configuration updates, and log collection, helping users conveniently manage and operate files in containers.
other extensions