用 kubectl 在 pod 中执行 bash 命令?

我的问题很简单。

如何在吊舱中执行 bash 命令? 我想用一个 bash 命令做所有的事情?

[root@master ~]# kubectl exec -it --namespace="tools" mongo-pod --bash -c "mongo"
Error: unknown flag: --bash

因此,该命令被简单地忽略。

[root@master ~]# kubectl exec -it --namespace="tools" mongo-pod bash -c "mongo"
root@mongo-deployment-78c87cb84-jkgxx:/#

差不多吧。

[root@master ~]# kubectl exec -it --namespace="tools" mongo-pod bash mongo
Defaulting container name to mongo.
Use 'kubectl describe pod/mongo-deployment-78c87cb84-jkgxx -n tools' to see all of the containers in this pod.
/usr/bin/mongo: /usr/bin/mongo: cannot execute binary file
command terminated with exit code 126

如果它只是一个重击,那么它当然可以工作。但是我想马上跳入 mongo shell。

我找到了一个解决办法,但它不工作。告诉我,如果这是可能的吗? 在 kubernetes pod 中执行多个命令(或从 shell 脚本)

谢谢。

190364 次浏览

The double dash symbol "--" is used to separate the command you want to run inside the container from the kubectl arguments. So the correct way is:

kubectl exec -it --namespace=tools mongo-pod -- bash -c "mongo"

You forgot a space between "--" and "bash".

To execute multiple commands you may want:

  • to create a script and mount it as a volume in your pod and execute it

  • to launch a side container with the script and run it

I use something like this to get into the pod's shell:

    kubectl exec -it --namespace develop pod-name bash

then you can execute the command you want within the pod (e.g. ping)

    ping www.google.com

then you can see your ping log and voila ... enjoy it :D