Skip to content
Kubernetes

Labels & Selectors

Tag resources and query them with selectors.

By EZ4Code Team
labelsselectorsquery

Code

# Add labels to a deployment
metadata:
  labels:
    app: api
    tier: backend
    env: prod

# kubectl commands using selectors
kubectl get pods -l app=api
kubectl get pods -l 'env in (prod,staging),tier=backend'
kubectl get pods -l env!=dev
kubectl delete pods -l app=api

# Show labels
kubectl get pods --show-labels
kubectl label pod api-pod version=v2
kubectl label pod api-pod version-   # remove label

# Node selector in a Pod
spec:
  nodeSelector:
    disktype: ssd

Explanation

Labels are key-value pairs attached to resources for grouping and querying, while selectors choose resources based on those labels. Equality, set-based (in, notin), and existence operators are supported. Many controllers and Services use label selectors to find the Pods they manage.

More Kubernetes Snippets