Copying Files Between Pods Using kubectl
Kubernetes provides the kubectl cp
command to copy files and directories between a local filesystem and a Pod, or between Pods. This feature is particularly useful when you need to transfer files or logs between different components of your application running in Kubernetes.
Copying Files from Local to Pod
To copy a file from your local filesystem to a Pod, use the following command:
kubectl cp <local_file_path> <namespace>/<pod_name>:<remote_file_path>
For example, to copy a file named my_file.txt
from the current directory to the /tmp
directory of a Pod named my-pod
in the default
namespace:
kubectl cp my_file.txt default/my-pod:/tmp
Copying Files from Pod to Local
To copy a file from a Pod to your local filesystem, use the following command:
kubectl cp <namespace>/<pod_name>:<remote_file_path> <local_file_path>
For example, to copy a file named logs.txt
from the /var/log
directory of a Pod named my-pod
in the default
namespace to the current directory:
kubectl cp default/my-pod:/var/log/logs.txt logs.txt
Copying Files Between Pods
You can also use the kubectl cp
command to copy files between Pods. The syntax is similar to the previous examples, but you need to specify the source and destination Pods:
kubectl cp <namespace>/<source_pod_name>:<remote_file_path> <namespace>/<destination_pod_name>:<remote_file_path>
For instance, to copy a file named data.csv
from the /data
directory of a Pod named source-pod
to the /backup
directory of a Pod named destination-pod
, both in the default
namespace:
kubectl cp default/source-pod:/data/data.csv default/destination-pod:/backup
By mastering the kubectl cp
command, you can easily manage file transfers between your local environment and Kubernetes Pods, as well as between Pods within your cluster, which is a common task in Kubernetes-based application development and maintenance.