You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Go客户端将本地文件复制到Minikube集群的Pod容器中

如何用kubectl Go客户端实现本地文件复制到Pod容器?

我有本地文件file.txt,想要将其复制到Podpod1的容器container1中,对应的kubectl命令为:kubectl cp file.txt pod1:file.txt -c container1。但不知道如何通过kubectl的Go客户端实现该操作,尝试了两种方法均未成功:

第一种尝试方法(报错)

代码如下:

import (
    "fmt"
    "context"
    "log"
    "os"
    "path/filepath"

    g "github.com/sdslabs/katana/configs"
    v1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/labels"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
    //"k8s.io/kubectl/pkg/cmd/exec"
)

func CopyIntoPod(namespace string, podName string, containerName string, srcPath string, dstPath string) {
    // Create a Kubernetes client
    config, err := GetKubeConfig()
    if err != nil {
        log.Fatal(err)
    }

    client, err := kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatal(err)
    }

    // Build the command to execute
    cmd := []string{"cp", srcPath, dstPath}

    // Use the PodExecOptions struct to specify the options for the exec request
    options := v1.PodExecOptions{
        Container: containerName,
        Command:   cmd,
        Stdin:     false,
        Stdout:    true,
        Stderr:    true,
        TTY:       false,
    }
    log.Println("Options set!")

    // Use the CoreV1Api.Exec method to execute the command inside the container
    req := client.CoreV1().RESTClient().Post().
        Namespace(namespace).
        Name(podName).
        Resource("pods").
        SubResource("exec").
        VersionedParams(&options, metav1.ParameterCodec)
    log.Println("Request generated")
    
    exec, err := req.Stream(context.TODO())
    if err != nil {
        log.Fatal(err)
    }
    defer exec.Close()

    // Read the response from the exec command
    var result []byte
    if _, err := exec.Read(result); err != nil {
        log.Fatal(err)
    }

    fmt.Println("File copied successfully!")
}

运行报错:no kind is registered for the type v1.PodExecOptions in scheme "pkg/runtime/scheme.go:100"

第二种尝试方法(Run方法执行失败)

代码如下:

type PodExec struct {
    RestConfig *rest.Config
    *kubernetes.Clientset
}

func NewPodExec(config *rest.Config, clientset *kubernetes.Clientset) *PodExec {
    config.APIPath = "/api" // Make sure we target /api and not just /
    config.GroupVersion = &schema.GroupVersion{Version: "v1"} // this targets the core api groups so the url path will be /api/v1
    config.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: scheme.Codecs}
    return &PodExec{
      RestConfig: config,
      Clientset:  clientset,
    }  
}

func (p *PodExec) PodCopyFile(src string, dst string, containername string, podNamespace string) (*bytes.Buffer, *bytes.Buffer, *bytes.Buffer, error) {
    ioStreams, in, out, errOut := genericclioptions.NewTestIOStreams()
    copyOptions := cp.NewCopyOptions(ioStreams)
    copyOptions.Clientset = p.Clientset
    copyOptions.ClientConfig = p.RestConfig
    copyOptions.Container = containername
    copyOptions.Namespace = podNamespace
    err := copyOptions.Run()
    if err != nil {
        return nil, nil, nil, fmt.Errorf("could not run copy operation: %v", err)
    }
    return in, out, errOut, nil
}

问题说明:调用copyOptions.Run()时,代码试图访问o.args[0],但由于未导入相关结构体,无法修改o导致执行失败。

疑问

目前不知道该如何解决上述问题,另外想到可以通过cmd.exec()直接调用kubectl cp命令实现,但感觉这种方式不够优雅,想咨询这个方案是否可行?


内容的提问来源于stack exchange,提问作者infinite-blank-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:45:30