Login to Kubernetes Pods, without knowing pod names ?

There are many ways to login to kubernetes pods, and most of them requires you to know the pod name.

Now let’s say we want to login to a pod that is being served by a service we want to troubleshoot. One longer way could be to first determine all the pods running behind service, and then login to those pods.  

We have an article on POCGuru vto do exact same thing – https://pocguru.com/2022/list-pods-behind-a-service-in-openshift/. But this is not very efficient when you are troubleshooting and have multiple types of pods running in namespace, one reason is because pod names are not constant, and get changed every time they are refreshed. On the other hand, generally we don’t change Service, Deployment or StatefulSet names that often, and can remember them or type them easily.

Instead, we can use kubectl to directly login to a service pod !

Bash
# let's get(confirm) the Service name first.

$ oc get svc mongodb-service 

  NAME              TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)     AGE 
  mongodb-service   ClusterIP   None         <none>        27017/TCP   287d 
  
# let's login to pod running behind a service, without typing pod name.

$ oc exec -it svc/mongodb-service -- bash 

mongodb@mongodb-statefulset-0:/$ 

# OR if using openshift oc utility  

$ oc rsh svc/mongodb-service bash 

mongodb@mongodb-statefulset-0:/$

Note: – Above command(s) will login to first pod of the service mongodb-service (in case you have multiple pods), using the first container by default. 

POCGuru - Login to Kubernetes pods.
POCGuru – Login to K8 Service Pod directly.

Bonus: – As a matter of fact, we can use the same logic for logging into pods created by kubernetes Deployment or StatefulSets.

Here is an example of logging into a pod created by StatefulSet, without knowing/typing the pod name.

Bash
#List StatefulSet

$ oc get statefulset             

NAME                  READY   AGE 
mongodb-statefulset   1/1     84d 

# Login to first pod created by StatefulSet, without typing pod name.

$ kubectl exec -it statefulset/mongodb-statefulset -- bash 
mongodb@mongodb-statefulset-0:/$  

# OR if using openshift oc utility  

$ oc rsh statefulset/mongodb-statefulset 
$ bash 
mongodb@mongodb-statefulset-0:/$  

POCGuru - Login to StatefulSet pod, without knowing pod name.

Hope you will find this useful, thank you.

Here is a Youtube video link explaining the same.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.