kubectl exec failed with "container <command> is not valid for pod <pod_name>"

7/22/2018

I am working with Minikube and I have alpine pod with one container.
When I run:
kubectl exec -it -v=6 alpinec1-7c65db48b4-v2gpc /bin/sh

I receive a shell and I can run any command (ifconfig, etc.) inside it.

But when I tried to run sh with -c it failed:

root:~# kubectl exec -it -v=6 alpinec1-7c65db48b4-v2gpc /bin/sh -c 'ifconfig'
I0722 05:45:25.091111   80392 loader.go:357] Config loaded from file /home/root/.kube/config
I0722 05:45:25.111876   80392 round_trippers.go:405] GET https://192.168.190.143:8443/api/v1/namespaces/default/pods/alpinec1-7c65db48b4-v2gpc 200 OK in 16 milliseconds
I0722 05:45:25.232564   80392 round_trippers.go:405] POST https://192.168.190.143:8443/api/v1/namespaces/default/pods/alpinec1-7c65db48b4-v2gpc/exec?command=%2Fbin%2Fsh&container=ifconfig&container=ifconfig&stdin=true&stdout=true&tty=true 400 Bad Request in 13 milliseconds
                                                                     I0722 05:45:25.232921   80392 helpers.go:201] server response object: [{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "container ifconfig is not valid for pod alpinec1-7c65db48b4-v2gpc",
  "reason": "BadRequest",
  "code": 400
}]
F0722 05:45:25.233095   80392 helpers.go:119] Error from server (BadRequest): container ifconfig is not valid for pod alpinec1-7c65db48b4-v2gpc
-- E235
kubectl
kubernetes
minikube

1 Answer

7/22/2018

kubectl interprets the -c flag not as a flag for ifconfig, but as a flag for the kubectl exec command itself -- which specifies the exact container of a Pod in which the command should be executed; this is also the reason that kubectl looks for a container named "ifconfig" in your Pod. See the documentation for more information.

Instead, use -- to denote flags that should not be interpreted by kubectl exec any more but instead be passed to the invoked command (ifconfig, in this case) as-is:

$ kubectl exec -it -v=6 alpinec1-7c65db48b4-v2gpc -- /bin/sh -c 'ifconfig'

Also note that in this case, you do not really need to invoke ifconfig from a shell; you could also just directly call ifconfig without using /bin/sh:

$ kubectl exec -it -v=6 alpinec1-7c65db48b4-v2gpc -- ifconfig
-- helmbert
Source: StackOverflow