Kubernetes copy file from pod to local

Kubernetes client kubectl provides cp sub command to copy file from pod to local filesystem or from local filesystem to pod.

You can use the kubectl cp command to copy files from a pod to your local system.
The syntax for the command is as follows:

kubectl cp <namespace>/<pod-name>:<pod-file-path> <local-file-path>

For example, if you have a pod named “my-pod” in the “my-namespace” namespace and you want to copy the file “config.json” from the pod’s “/etc/config” directory to your local system’s “/tmp” directory, you can use the following command:

kubectl cp my-namespace/my-pod:/etc/config/config.json /tmp/config.json

You can also copy files from a container within a pod to your local system, by specifying the container name after the pod name.

kubectl cp my-namespace/my-pod:container-name:/etc/config/config.json /tmp/config.json


to run this command tar utility should already be installed on the pod.

kubctl cp equals to the following command:

#Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace
tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar xf - -C /tmp/bar

#Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl exec -n <some-namespace> <some-pod> -- tar cf - /tmp/foo | tar xf - -C /tmp/bar

It’s important to note that the kubectl cp command uses the container’s filesystem, not the host’s filesystem, which means that you can only copy files that are present within the container’s filesystem and not on the host. Additionally, you need to have permissions to access the pod or container and the pod should be running.

An alternative way is to use kubectl exec command to open a shell inside the pod and use standard commands such as cp, scp or tar to copy the files.

kubectl exec -it my-pod -c container-name -- bash

Once you’re inside the pod, you can copy the files using the standard commands.

cp /etc/config/config.json /tmp/config.json

You can then use exit command to exit the pod’s shell, and use scp to copy the file from the pod to your local machine.

Leave a Reply

Your email address will not be published. Required fields are marked *