Run an interactive shell in a kubernetes cluster

2 min read | by Jordi Prats

For troubleshooting purposes, it's quite useful to run an interactive shell on the kubernetes cluster. We can always run a shell con an existing container but it might not have the tools we need.

To be able to run a container we need to take a look at the kubectl run options:

  • --rm: Since it is for troubleshooting, we do want to make sure to delete the container as soon as we are done with it
  • -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

We will have to also choose the right image, maybe a busybox can be enough but an image with troubleshooting tools such as netshoot might be really useful.

The full command would for shell in a netshoot container would be:

$ kubectl run k8s-shell --rm -it --image nicolaka/netshoot -- sh
If you don't see a command prompt, try pressing enter.
/ # ps
PID   USER     TIME  COMMAND
    1 root      0:00 sh
    8 root      0:00 ps
/ # 
Session ended, resume using 'kubectl attach k8s-shell -c k8s-shell -i -t' command when the pod is running
pod "k8s-shell" deleted

Is we want to use busybox instead it would be:

$ kubectl run busyshell --rm -it --image busybox -- sh
If you don't see a command prompt, try pressing enter.
/ # uname -a
Linux busyshell 5.8.0-36-generic #40~20.04.1-Ubuntu SMP Wed Jan 6 10:15:55 UTC 2021 x86_64 GNU/Linux
/ # 
Session ended, resume using 'kubectl attach busyshell -c busyshell -i -t' command when the pod is running
pod "busyshell" deleted

Posted on 03/02/2021