Kubernetes (kubectl) get running pods

9/28/2017

I am trying to get the first pod from within a deployment (filtered by labels) with status running - currently I could only achieve the following, which will just give me the first pod within a deployment (filtered by labels) - and not for sure a running pod, e.g. it might also be a terminating one:

kubectl get pod -l "app=myapp" -l "tier=webserver" -l "namespace=test" 
                -o jsonpath="{.items[0].metadata.name}"

How is it possible to

a) get only a pod list of "RUNNING" pods and (couldn't find anything here or on google)

b) select the first one from that list. (thats what I'm currently doing)

Regards

Update: I already tried the link posted in the comments earlier with the following:

kubectl get pod -l "app=ms-bp" -l "tier=webserver" -l "namespace=test"  
-o json | jq -r '.items[] | select(.status.phase = "Running") | .items[0].metadata.name'

the result is 4x "null" - there are 4 running pods.

Edit2: Resolved - see comments

-- user3746259
go
json
kubectl
kubernetes

1 Answer

10/23/2019

Since kubectl 1.9 you have the option to pass a --field-selector argument (see https://github.com/kubernetes/kubernetes/pull/50140). E.g.

kubectl get pod -l app=yourapp --field-selector=status.phase==Running -o jsonpath="{.items[0].metadata.name}"
-- David Ongaro
Source: StackOverflow