Using kubectl exec to run an interactive shell on an existing pod

2 min read | by Jordi Prats

It's quite common to at least have a shell installed on the containers since it's footprint on the kB range. Let's check how to get an interactive shell on a running Pod. In case the pod we want to connect to is just using one container like in this example:

$ kubectl get pods 
NAME                                     READY   STATUS      RESTARTS   AGE
pet2cattle-s3sync-5f9b9486cf-nznph       1/1     Running     0          2m20s

We can use kubectl exec with the following options:

  • -i: Keep stdin open to the container in the pod, since we want to have som interaction with it
  • -t: Allocation of a TTY is required

Once we have specified the pod we want to use, we can use two dashes to specify any command (even options). With the double dashes we are telling the interpreter that after it there won't be any options, all should be interpreted as a literal:

$ kubectl  exec -it pet2cattle-s3sync-5f9b9486cf-nznph -- sh
/code # 

In case the pod contains several containers (notice the 2/2 on the READY column):

$ kubectl get pods -n ampa
NAME                                     READY   STATUS      RESTARTS   AGE
ampa-576776657f-ph7bc                    2/2     Running     0          4d14h

To be able to get the name of the containers we will can either use jsonpath of just take a look at the YAML definition

$ kubectl get pod ampa-576776657f-ph7bc -o=jsonpath='{range .spec.containers[*]}{.name}{"\n"}{end}'
ampa
ampa-processing

Either way, once we have the container name we just need to use the -c to specify to which container we want to execute the command:

$ kubectl exec -it ampa-576776657f-ph7bc -c ampa-processing -- sh
/code # 

Posted on 18/02/2021