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

在PodExecOptions中指定容器不生效的问题排查求助

问题

我希望在Golang中实现与kubectl exec -it POD -c CONTAINER -- CMD等效的功能。该Pod包含多个容器,因此我需要指定目标容器。

以下是相关代码片段:

import (
...
    v1 "k8s.io/api/core/v1"
...
)

....

    podName := "<pod-name-here>"
    containerName := "<container-name-goes-here"
    namespace := "<namespace-here>"
    cmd := []string{"/bin/sh", "-c", "echo Hello World"}

    req := clientset.CoreV1().RESTClient().
        Post().
        Resource("pods").
        Name(podName).
        Namespace(namespace).
        SubResource("exec").
        VersionedParams(&v1.PodExecOptions{
            Command:   cmd,
            Container: containerName,
            Stdin:     false,
            Stdout:    true,
            Stderr:    true,
            TTY:       false,
        }, metav1.ParameterCodec)

    // Create buffers to capture stdout and stderr
    var stdout, stderr bytes.Buffer

    exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
    if err != nil {
        panic(err)
    }

    // Create a context to manage the stream's lifecycle
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel() // Cancel the context when done to clean up resources

    err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{
        Stdin:  nil,
        Stdout: &stdout, // Capture stdout here
        Stderr: &stderr, // Capture stderr here
        Tty:    false,
    })
    if err != nil {
        panic(err)
    }

但持续收到如下错误:

panic: a container name must be specified for pod POD, choose one of: [CONTAINER1 CONTAINER2 CONTAINER3]

我已经在PodExecOptions中指定了容器名称,为何还会出现该错误?请问有哪些排查建议?

排查建议
  • 修复变量语法错误:代码中containerName := "<container-name-goes-here"少了闭合双引号,导致变量值不完整,K8s无法识别正确的容器名称,先补上这个引号。
  • 核对容器名拼写:确认containerName的值和错误提示里列出的容器名完全一致,K8s对容器名的大小写、特殊字符严格敏感,不能有拼写错误或空格差异。
  • 检查请求参数是否传递成功:打印req.URL()查看生成的请求URL,确认query参数中包含container=你的容器名。如果没有,说明VersionedParams可能未正确编码参数,可以尝试在SubResource("exec")之后手动添加.Param("container", containerName)。
  • 验证client-go版本兼容性:确保使用的client-go版本与K8s集群版本匹配,部分旧版本在处理exec子资源的参数传递时存在bug,可升级到与集群兼容的稳定版本。
  • 手动验证kubectl命令:先用kubectl exec -it <pod-name-here> -c <container-name-goes-here> -- /bin/sh -c "echo Hello World"执行命令,确认该命令本身能正常运行,排除容器不存在、权限不足等问题。

内容的提问来源于stack exchange,提问作者jersey bean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:00:33