有时候需要想把服务器本地的文件复制到远程k8s中正在运行的容器里或实现逆向文件复制,可以通过kubectl的cp命令完成这个需求。
注意,此命令需要双方的系统环境里已安装tar工具,否则无法使用
# kubectl cp --help
Copy files and directories to and from containers.
Examples:
# !!!Important Note!!!
# Requires that the 'tar' binary is present in your container
# image. If 'tar' is not present, 'kubectl cp' will fail.
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
# Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
# Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
Options:
-c, --container='': Container name. If omitted, the first container in the pod will be chosen
Usage:
kubectl cp <file-spec-src> <file-spec-dest> [options]
Use "kubectl options" for a list of global command-line options (applies to all commands).
从容器复制文件到本地:
kubectl cp <namespace>/<pod>:<root_dir>/<parent_dir>/<file_name> ./<file_name>
注:pod冒号后直接加根目录,不能加“/”,否则报错 tar: removing leading ‘/’ from member names
本地及远程地址都只能使用相对路径, 而且本地的路径不能有层级
从本地复制到容器:
kubectl cp ./<file_name> <namespace>/<pod>:/<root_dir>/<parent_dir>/<file_name>
本地及远程地址都可使用绝对路径或者相对路径
本地地址的相对目录为当前kubectl执行命令的目录,远程地址的目录为pod workdir的目录
从Pod容器中copy文件至本地
kubectl cp -c cloud-loan-gate uat/cloud-786d84c554-p7jz7:app/logs/server.log ./server.log
uat 为namespace
-c 指定容 因pod中有多个container,默认从第一个,有可能报错找不到文件和目录
源目录参数 后只能跟文件名,不能是以“/”开头的路 必须是 app/logs/server.log
目标参数 必须为文件不能是一个目录 ,如 /tmp/server.log
参考
Kubectl cp使用注意事项
https://developer.aliyun.com/article/788714
使用kubectl cp在pod和主机之间拷贝文件
https://blog.csdn.net/LONG_Yi_1994/article/details/123988713
k8s kubectl 在本地和容器之间复制文件
https://blog.csdn.net/zhoudingding/article/details/122403358
Kubectl cp gives "tar: removing leading '/' from member names" warning
https://github.com/kubernetes/kubernetes/issues/58692
How to copy files from kubernetes Pods to local system
https://stackoverflow.com/questions/52407277/how-to-copy-files-from-kubernetes-pods-to-local-system
命令行工具 (kubectl)
https://kubernetes.io/zh-cn/docs/reference/kubectl/











网友评论