tumm
tumm

Reputation: 163

How to get number of pods (available or terminating) in kubernetes?

I need to find the number of pods currently NOT terminated (can be available, terminating, etc.) in order to prevent deployment from starting if there are still some pods not terminated.

UPDATE: If there are no pods available, I should get "0". Is it possible ?

Upvotes: 16

Views: 46706

Answers (4)

Blokje5
Blokje5

Reputation: 5003

You can try:

kubectl get pods --field-selector=status.phase!=Succeeded,status.Phase!=Failed

If you look at the Pod Phases you can see that this covers all possible pods where all containers are terminated (either failed or succeeded)

If you specifically want the count you could use a bit of jq and use:

kubectl get pods --field-selector=status.phase!=Succeeded,status.phase!=Failed --output json | jq -j '.items | length'

This returns the # of pods that are not Terminated.

Upvotes: 25

Marridi
Marridi

Reputation: 91

If you are on Linux, you can use the command line tool wc (wordcount) to count the lines of kubectl (combined with the no headers option) like this:

kubectl get pods --no-headers | wc -l

Upvotes: 9

user7610
user7610

Reputation: 28811

As an alternative to the jq answer, here is a wc -l answer

k3s kubectl get pods --output name | wc -l

This is somewhat more convenient in that jq may not be always installed.

Upvotes: 5

Jose Armesto
Jose Armesto

Reputation: 13759

If your use case is making sure you only have a single instance/replica of your application running at any given time, maybe it's better to rely on built-in Kubernetes options to handle that.

You can configure your Deployment object using replicas, maxUnavailable and maxSurge to control how many instances are created of your application.

Upvotes: 0

Related Questions