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 !
# 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.
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.
#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:/$
Hope you will find this useful, thank you.
Here is a Youtube video link explaining the same.