Copying Files Between Kubernetes Pods and Local Machines
The kubectl cp
command provides a convenient way to transfer files between your local machine and Kubernetes pods. This can be useful in a variety of scenarios, such as:
- Transferring log files or other diagnostic information from a pod to your local machine for analysis
- Copying application code or configuration files from your local development environment to a pod for deployment
- Transferring data or assets required by an application from your local machine to a pod
Copying Files from Local to Pod
To copy a file from your local machine to a Kubernetes pod, use the following syntax:
kubectl cp /path/to/local/file.txt <namespace>/<pod-name>:/path/to/remote/file.txt
Replace /path/to/local/file.txt
with the path to the file on your local machine, and <namespace>/<pod-name>:/path/to/remote/file.txt
with the destination path within the target pod.
For example, to copy a file named app.log
from your local machine to the /logs
directory of a pod named my-app
in the default
namespace, you would run:
kubectl cp /path/to/app.log default/my-app:/logs/app.log
Copying Files from Pod to Local
To copy a file from a Kubernetes pod to your local machine, use the following syntax:
kubectl cp <namespace>/<pod-name>:/path/to/remote/file.txt /path/to/local/file.txt
Replace <namespace>/<pod-name>:/path/to/remote/file.txt
with the path to the file within the target pod, and /path/to/local/file.txt
with the destination path on your local machine.
For example, to copy a file named app.log
from the /logs
directory of a pod named my-app
in the default
namespace to your local machine, you would run:
kubectl cp default/my-app:/logs/app.log /path/to/local/app.log
Copying Directories
The kubectl cp
command also supports copying directories between your local machine and Kubernetes pods. The syntax is similar to the file copying examples, but you'll need to use the /
character at the end of the directory path to indicate that it's a directory.
## Copy a directory from local to pod
kubectl cp /path/to/local/directory <namespace>/<pod-name>:/path/to/remote/directory/
## Copy a directory from pod to local
kubectl cp <namespace>/<pod-name>:/path/to/remote/directory/ /path/to/local/directory
In the next section, we'll explore some advanced use cases for the kubectl cp
command.