Understanding the Docker CP Command
The docker cp
command is a powerful tool in the Docker ecosystem that allows you to copy files and directories between a Docker container and the host file system, or between two Docker containers.
Syntax of the Docker CP Command
The basic syntax of the docker cp
command is as follows:
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Here, CONTAINER
is the name or ID of the Docker container, SRC_PATH
is the source path (either on the host or inside the container), and DEST_PATH
is the destination path (either on the host or inside the container).
Copying Files from a Container to the Host
To copy a file from a running container to the host file system, you can use the following command:
docker cp CONTAINER:SRC_PATH DEST_PATH
For example, to copy a file named app.log
from a container named my-app
to the current directory on the host, you would run:
docker cp my-app:/app/app.log .
Copying Files from the Host to a Container
To copy a file from the host file system to a running container, you can use the following command:
docker cp SRC_PATH CONTAINER:DEST_PATH
For example, to copy a file named config.yaml
from the current directory on the host to the /app
directory inside a container named my-app
, you would run:
docker cp config.yaml my-app:/app
Copying Files Between Containers
You can also use the docker cp
command to copy files between two running containers. To do this, you'll need to specify the source container, source path, destination container, and destination path:
docker cp CONTAINER1:SRC_PATH CONTAINER2:DEST_PATH
For example, to copy a file named data.csv
from a container named container1
to a container named container2
, you would run:
docker cp container1:/data/data.csv container2:/data
Advanced Copying Techniques
The docker cp
command also supports additional options, such as:
-L
: Follow symbolic links in the source container.
-a
: Preserve permissions and ownership.
-p
: Preserve file metadata (e.g., modification times).
These options can be useful in more advanced use cases, such as when you need to preserve file permissions or follow symbolic links during the copy operation.