Kubernetes sort pods by age

KubernetesKubectlKubernetes Pod

Kubernetes Problem Overview


I can sort my Kubernetes pods by name using:

kubectl get pods --sort-by=.metadata.name

How can I sort them (or other resoures) by age using kubectl?

Kubernetes Solutions


Solution 1 - Kubernetes

Pods have status, which you can use to find out startTime.

I guess something like kubectl get po --sort-by=.status.startTime should work.

You could also try:

  1. kubectl get po --sort-by='{.firstTimestamp}'.
  2. kubectl get pods --sort-by=.metadata.creationTimestamp Thanks @chris

Also apparently in Kubernetes 1.7 release, sort-by is broken.

https://github.com/kubernetes/kubectl/issues/43

Here's the bug report : https://github.com/kubernetes/kubernetes/issues/48602

Here's the PR: https://github.com/kubernetes/kubernetes/pull/48659/files

Solution 2 - Kubernetes

kubectl get pods --sort-by=.metadata.creationTimestamp

Solution 3 - Kubernetes

If you are trying to get the most recently created pod you can do the following

kubectl get pods --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1:].metadata.name}'

Note the -1: gets the last item in the list, then we return the pod name

Solution 4 - Kubernetes

If you want to sort them in reverse order based on the age:

kubectl get po --sort-by=.metadata.creationTimestamp -n <<namespace>> | tac

Solution 5 - Kubernetes

If you want just the name of most-recently-created pod;

POD_NAME=$(kubectl get pod --sort-by=.metadata.creationTimestamp -o name | cut -d/ -f2 | tail -n 1)
echo "${POD_NAME}"

Solution 6 - Kubernetes

I wanted to see all pods that were updated in the past 24 hours. This worked perfectly well and doesn't rely on a particular version of Kubernetes or Kubernetes advanced parameters besides get pods:

kubectl get pods | awk '{print $1 " : " $5}' | grep -E ':\s([1-9]|[12][0-4])h$' | sort -k3,3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEugene PlatonovView Question on Stackoverflow
Solution 1 - KubernetesvjdhamaView Answer on Stackoverflow
Solution 2 - KubernetesChris StryczynskiView Answer on Stackoverflow
Solution 3 - KubernetesAntony DenyerView Answer on Stackoverflow
Solution 4 - KubernetesimrissView Answer on Stackoverflow
Solution 5 - KubernetesSteve CooperView Answer on Stackoverflow
Solution 6 - KubernetesjamescampbellView Answer on Stackoverflow