Sign In

Curriculum 7: Reading & Inspecting

kubectl get Deep Dive

15 min · 15 XP

Advanced kubectl get

You already know kubectl get lists resources. This lesson covers the advanced options that make it a powerful query tool.

Field Selectors

Field selectors filter resources by their actual field values, not labels:

# Get pods on a specific node
kubectl get pods --field-selector spec.nodeName=worker-1

# Get pods that are not running
kubectl get pods --field-selector status.phase!=Running

# Combine multiple field selectors
kubectl get pods --field-selector status.phase=Running,spec.nodeName=worker-2

# Get events for a specific reason
kubectl get events --field-selector reason=BackOff

Field selectors support a limited set of fields. Not every field is selectable. The universally supported fields are metadata.name, metadata.namespace, and for most resources status.phase.

Sorting

Sort output by any field using JSONPath:

# Sort pods by creation time
kubectl get pods --sort-by=.metadata.creationTimestamp

# Sort pods by restart count
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

# Sort nodes by capacity
kubectl get nodes --sort-by=.status.capacity.cpu

Custom Columns

Build exactly the table you need:

# Pod name, status, and node
kubectl get pods -o custom-columns=\
NAME:.metadata.name,\
STATUS:.status.phase,\
NODE:.spec.nodeName,\
IP:.status.podIP

# Deployment name, replicas desired vs available
kubectl get deploy -o custom-columns=\
NAME:.metadata.name,\
DESIRED:.spec.replicas,\
AVAILABLE:.status.availableReplicas

You can also define custom columns in a file:

# columns.txt
NAME          JSONPATH
Pod           .metadata.name
Status        .status.phase
Restarts      .status.containerStatuses[0].restartCount

kubectl get pods -o custom-columns-file=columns.txt

Label Selectors

Filter by labels using set-based or equality-based expressions:

# Equality-based
kubectl get pods -l app=nginx
kubectl get pods -l 'environment!=production'

# Set-based
kubectl get pods -l 'app in (nginx, apache)'
kubectl get pods -l 'tier notin (frontend)'
kubectl get pods -l '!canary'

Combining Options

Chain multiple options together for precise queries:

# Running pods on worker-1, sorted by age, with custom output
kubectl get pods \
  --field-selector spec.nodeName=worker-1,status.phase=Running \
  --sort-by=.metadata.creationTimestamp \
  -o custom-columns=NAME:.metadata.name,AGE:.metadata.creationTimestamp

Key Takeaways

  • Field selectors filter by resource fields like node name and status phase
  • --sort-by accepts any JSONPath expression for sorting
  • Custom columns let you build tailored output tables
  • Label selectors support both equality and set-based expressions
  • Combining these options creates powerful queries without external tools