5

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>
Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102
prosenjit
  • 805
  • 3
  • 9
  • 10

3 Answers3

13
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
Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102
  • Thanks for your reply. I have already created a command to print pod_name, container name and status. kubectl get po -A -o jsonpath='{range .items[*]}{"pod: "}{.metadata.name}{"\n"}{range .status.containerStatuses[*]}{"\tcontainer_name: "}{.name}{"\n\tcontainer_status: "}{.ready}{"\n"}{end}' But I want the container without running status. – prosenjit Dec 23 '20 at 10:38
  • i think above command share is printing the container in not running state only maybe. – Harsh Manvar Sep 15 '22 at 11:54
  • 1
    This does not seem to list pods that are have a status of CrashLoopBackOff. – Chris Stryczynski Mar 17 '23 at 13:48
  • coz for crashingLoopBackOff phase of POD will be Running only as it's Running but crashing so ideally not get listed with above command. – Harsh Manvar Mar 17 '23 at 14:19
2

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}'
lenkovi
  • 1,708
  • 2
  • 11
  • 16
0

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}'