235

Reading the Kubernets documentation it looks to be possible to select a certain range of pods based on labels. I want to select all the pods on one node but I don't want to label each pod on their corresponding node.

Am I missing something from the documentation or is it just not possible to select by node?

If I do:

kubectl get pods \
--output=wide
--namespace=$NS \
--server=$SERVER | head

#=>

NAME   READY     STATUS             RESTARTS   AGE       NODE

Can any of these headers be used as selector? If yes, how to do it with kubectl? How to do it with the API?

Mike
  • 1,080
  • 1
  • 9
  • 25
Fran
  • 3,693
  • 4
  • 19
  • 19
  • 2
    Please consider changing the accepted answer, as the current accepted answer is deprecated. – deiga Jan 31 '20 at 07:54

6 Answers6

447

As mentioned in the accepted answer the PR is now merged and you can get pods by node as follows:

kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>
Kristofer
  • 7,861
  • 6
  • 30
  • 31
  • 2
    I have a clarification: this `--all-namespaces` is going to first pull all pods from entire cluster and then its going to filter for node? or is it just going to pull all pods from that node only without heavily pulling all namespaces pods from entire cluster? – AhmFM Jun 11 '20 at 13:19
  • According to the K8s API documentation: >>> NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements. ...so, first of all, nodeName is optional - and second, there is no mention here that the Scheduler populates this field when it assigns a Pod to a Node. Is this relying on undocumented behavior? (Reference: https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#scheduling) – Bartek Muszynski Mar 20 '22 at 21:25
  • 2
    How do you query multiple nodes? – Shinebayar G Oct 11 '22 at 17:41
138

Example sorting pods by nodeName:

kubectl get pods -o wide --sort-by="{.spec.nodeName}"

Example of getting pods on nodes using label filter:

for n in $(kubectl get nodes -l your_label_key=your_label_value --no-headers | cut -d " " -f1); do 
    kubectl get pods --all-namespaces  --no-headers --field-selector spec.nodeName=${n} 
done

or by number of restarts

kubectl get pods --sort-by="{.status.containerStatuses[:1].restartCount}"

Example filtering by nodeName using --template flag:

$ kubectl get nodes

NAME                         STATUS                     AGE
ip-10-0-90-30.ec2.internal   Ready                      2d
ip-10-0-90-35.ec2.internal   Ready                      2d
ip-10-0-90-50.ec2.internal   Ready,SchedulingDisabled   2d
ip-10-0-91-60.ec2.internal   Ready                      2d
ip-10-0-91-65.ec2.internal   Ready                      2d


$kubectl get pods --template '{{range .items}}{{if eq .spec.nodeName "ip-10-0-90-30.ec2.internal"}}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'

filebeat-pezch
app-5xole
node-exporter-6kfs8
prometheus-0
sso-359976856-wu8zt
Camil
  • 7,800
  • 2
  • 25
  • 28
  • That's interesting that it's possible to sort by these data but the only thing that can be filtered by selector is what is on ".spec.selector". – Fran Aug 31 '16 at 10:32
  • 1
    The filters are executed server-side, sorting is client-side – Tim Hockin Aug 31 '16 at 23:06
  • you have a typo. extra brace needs to be removed: `kubectl get pods --template '{{range .items}}{{if eq .spec.nodeName "ip-10-0-90-30.ec2.internal"}}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'` – Priyesh Patel May 19 '23 at 16:09
28

You also can query for all pods an a node with the following command

kubectl get pods -o wide --all-namespaces | grep <YOUR-NODE>
Mal
  • 324
  • 3
  • 7
  • 1
    use -a also with kubectl ----- kubectl get pods -a -o wide --all-namespaces | grep – Pawan Kumar Jun 03 '18 at 04:33
  • 6
    This is actually querying for all pods (and then filtering in the client), which may be much slower in large clusters. The best solution would be @Kristofer 's answer. – Guilherme Garnier Apr 08 '19 at 18:44
  • 1
    I think, -a doesn't work anymore. We need to use '-A' instead something like, "kubectl get pods -A -owide | grep " – NightOwl19 Jan 14 '21 at 15:35
23
kubectl describe node $NODE

will show all of the non-terminated pods running on $NODE.

Mike
  • 1,080
  • 1
  • 9
  • 25
Matt Hamann
  • 1,488
  • 12
  • 24
  • Thanks this is something I want to get in the habit of taking better advantage of. There is a lot of good info I didn't expect in there. – Josiah Mar 28 '23 at 20:42
10

What you want is supported in the Kubernetes API server-side like this:

curl --cacert ca.crt --cert apiserver.crt --key apiserver.key  https://<server>:<port>/api/v1/namespaces/<namespace>/pods?fieldSelector=spec.nodeName%3Dsomenodename

However that field selector option is not built into kubectl yet: https://github.com/kubernetes/kubernetes/pull/50140

coreypobrien
  • 1,921
  • 17
  • 17
5

I've gone through the same process with the Go Client and it uncovers a few shortcuts the CLI is taking.

func doNodesHavePods(clientset *kubernetes.Clientset) error {
    nodeLabelSelector := "nodelabel=interesting_nodes"
    nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{LabelSelector: nodeLabelSelector})

    if err != nil {
        return err
    }

    nodeNames := []string{}
    for _, node := range nodes.Items {
        nodeNames = append(nodeNames, node.Name)
    }
    // --all-namespaces -> listing and looping on namespaces
    namespaces, err := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})

    if err != nil {
        return err
    }
    for _, namespace := range namespaces.Items {
        for _, name := range nodeNames {
            // pods need a namespace to be listed.
            pods, err := clientset.CoreV1().Pods(namespace.Name).List(metav1.ListOptions{FieldSelector: "spec.nodeName=" + name})
            if err != nil {
                println("%v", err)
            }
            for _, pod := range pods.Items {
                fmt.Println(pod.Namespace, pod.Name)
            }
        }
    }
    return nil
}

I've started to find that a lot of the questions I need to ask are becoming too complex for the CLI which is a great workhorse, but learning to use the Go Client can help you get the first answer you're looking for, but also dig deeper into questions that those answers raise.

Breedly
  • 12,838
  • 13
  • 59
  • 83