【问题标题】:How do I run a container from the command line in Kubernetes (like docker run)?如何从 Kubernetes 的命令行运行容器(如 docker run)?
【发布时间】:2021-09-13 01:12:23
【问题描述】:

我想在我的 Kubernetes 集群中通过命令行运行一次性容器。相当于:

docker run --rm -it centos /bin/bash

是否有 kubectl 等效项?

【问题讨论】:

    标签: kubernetes


    【解决方案1】:

    kubectl 相当于

    docker run --rm -it centos /bin/bash
    

    kubectl run tmp-shell --restart=Never --rm -i --tty --image centos -- /bin/bash
    

    注意事项:

    • 这将创建一个名为 tmp-shell 的 Pod。如果您不指定 --restart=Never,则会创建一个 Deploment(来源:Urosh T 的答案)。

    • --rm 确保在 shell 退出时删除 Pod。

    • 如果您想从 shell 中分离并让它运行并能够重新连接,请省略 --rm。然后,您可以在退出 shell 后重新附加:kubectl attach $pod-name -c $pod-container -i -t

    • 如果您的 shell 没有启动,请检查您的集群是否资源不足 (kubectl describe nodes)。您可以使用--requests 指定资源请求:

      --requests='': The resource requirement requests for this container.  For example, 'cpu=100m,memory=256Mi'.  Note that server side components may assign requests depending on the server configuration, such as limit ranges.
      

    (信用:https://gc-taylor.com/blog/2016/10/31/fire-up-an-interactive-bash-pod-within-a-kubernetes-cluster

    【讨论】:

    • kubectl run test-pod --generator=run-pod/v1 --image=busybox --image-pull-policy=IfNotPresent --restart=Never --rm --attach -- ping -c 5 google.com
    • @Dmitry 我在哪里可以找到此信息:$pod-container
    • @FelipePereira 您可以执行kubectl describe po $pod 之类的操作,它将列出在 pod 中运行的所有容器,其中 $pod 是部署创建的 pod 的名称。
    • 如果你有没有被污染的windows节点,你可能想试试kubectl run tmp-shell --restart=Never --rm -i --tty --image ubuntu --overrides='{"apiVersion": "v1", "spec": {"nodeSelector": { "beta.kubernetes.io/os": "linux" }}}' -- /bin/bash
    • 我们如何在命令中提供安全上下文?当我运行命令 kubectl run pod1 --restart=Never --rm -i --tty --image test1 --requests='cpu=1000m,memory=1000Mi' -n testnamespace -- /bin/bash 时出现错误“错误:容器已 runAsNonRoot 并且图像将以 root 身份运行”
    【解决方案2】:

    要创建 Pod 而不是 Deployment 并在退出时自行删除,请尝试以下操作:

    kubectl run curl-debug --rm -i --tty --restart=Never --image=radial/busyboxplus:curl -- /bin/sh
    

    --restart=Never 标志是用来创建 Pod 而不是 Deployment 对象的意思

    另外 - 此图像重量轻,下载速度快,适合网络调试。

    希望有帮助

    【讨论】:

    • 谢谢 Urosh!我更新了我的答案以包括--restart=Never
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2018-12-18
    • 1970-01-01
    相关资源
    最近更新 更多