Use “kubectl cp” to Copy Files to and from Kubernetes Pods

From the docs, here’s the basic usage:

kubectl cp <file-spec-src> <file-spec-dest>

The kubectl cp command takes two parameters. The first is the source; the second is the destination. As with scp, either parameter (source or destination files) can refer to a local or remote file.

Before we begin

We need to make sure our kubernetes client is authenticated with a cluster. There are many ways to authenticate, but authentication is outside the scope of this guide.

Second, we’ll need to identify the name of a pod (or pods) that we want to work with. We’ll need to use kubectl get pod to find the name of the pod(s), and we’ll use these names in the following sections.

Copy file from local machine to pod

Suppose we want to move a file from our local machine to a pod.

kubectl cp /path/to/file my-pod:/path/to/file

In the above example, we copied a local file /path/to/file to a pod named, my-pod. We’ve specified an identical path on the pod to copy the file. Notice that we used an absolute path in both cases. We can also use relative paths:

kubectl cp my-file my-pod:my-file

In this example, we’ve specified a relative path to a local file, and a relative path on the pod. One key difference between kubectl cp and a tool like scp is that with kubernetes, the file is copied relative to the working directory, not the home directory.

Copy file from a pod to a pod

Similarly, we can copy a file from one pod to another. The same rules for absolute and relative paths apply.

kubectl cp pod-1:my-file pod-2:my-file

Copy file from pod to your local machine

As you might have guessed, you simply swap the parameters from the first example.

kubectl cp my-pod:my-file my-file

This will copy my-file from the working directory of your pod to your current directory.

Copying directories

When using scp to copy directories, we’re accustomed to adding the -r (recursive) flag. With kubectl cp this is implied. You use the exact same syntax to copy directories is you would files.

kubectl cp my-dir my-pod:my-dir

Specifying a container

In some cases, you may be running multiple containers on a pod. In which case, you’ll need to specify the container. You can do so with -c, which is consistent with most other kubectl commands.

kubectl cp my-file my-pod:my-file -c my-container-name
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments