Kubernetes List All Containers that are not running

14.8k Views Asked by At

How to list All Containers that are not running using Kubectl command. I want output like

CONTAINER_NAME   STATUS        POD_NAME       NAMESPACE <br>
container_1      Running       pod_1          ns1       <br>
container_2      Not Running   pod_2          ns2       <br>
container_3      Running       pod_2          ns2       <br>
3

There are 3 best solutions below

4
Harsh Manvar On
kubectl get pods --field-selector status.phase!=Running

Above command will above list down all pods, not in Running status for default namespace.

if you want to run a command across all namespaces & list down all PODS

kubectl get pods --field-selector status.phase!=Running --all-namespaces

You can also print custom column as per require if you want to print Namespace

kubectl get pod --field-selector status.phase!=Running -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase,NAMEDPACE:.metadata.namespace

Final command the way you are looking forward with columns

kubectl get pod --field-selector status.phase!=Running -o=custom-columns=POD_NAME:.metadata.name,STATUS:.status.phase,NAMEDPACE:.metadata.namespace,CONTAINER_NAME:.spec.containers[*].name
0
Shivam Narula On

In Addition to above answer, I had a special usecase where I wanted to get all the non-running pods names to remove them. So I used this to get the names as list

kubectl get pods --all-namespace --field-selector status.phase!="Running" -o=jsonpath='{.items[*].metadata.name}'
0
lenkovi On

The issue here is that .status.phase is actually the scheduling state, not the actual state. It can be in "Running" state and your containers in the pod still in a crashloop. What I do is to check if the latest containerStatuses is in a waiting state. If yes, than those will be the stuck containers:

kubectl get pods -o jsonpath='{range .items[?(@.status.containerStatuses[-1:].state.waiting)]}{.metadata.name}: {@.status.containerStatuses[*].state.waiting.reason}{"\n"}{end}'