Kubernetes_labels_selectors
Chapter 25: Kubernetes Labels and Selectors - Organization and Discovery
Section titled “Chapter 25: Kubernetes Labels and Selectors - Organization and Discovery”Table of Contents
Section titled “Table of Contents”Introduction to Labels
Section titled “Introduction to Labels”What are Labels?
Section titled “What are Labels?”Labels are key-value pairs attached to Kubernetes objects. They are used to identify, organize, and select subsets of objects. Unlike names, labels are not unique and multiple labels can be attached to the same object.
┌─────────────────────────────────────────────────────────────────────────────┐│ KUBERNETES LABELS │├─────────────────────────────────────────────────────────────────────────────┤│ ││ ┌───────────────────────────────────────────────────────────────────┐ ││ │ POD │ ││ │ metadata: │ ││ │ labels: │ ││ │ app: myapp # Identify the application │ ││ │ tier: frontend # Tier (frontend, backend, db) │ ││ │ environment: production # Environment │ ││ │ version: v1.0.0 # Version of the app │ ││ │ team: platform # Team responsible │ ││ │ release: stable # Release channel │ ││ │ │ ││ └───────────────────────────────────────────────────────────────────┘ ││ ││ Labels allow you to: ││ • Group objects by characteristics ││ • Select specific objects for operations ││ • Organize resources logically ││ • Implement service discovery ││ │└─────────────────────────────────────────────────────────────────────────────┘Label Syntax
Section titled “Label Syntax”Label Format
Section titled “Label Format”# Labels in Pod definitionapiVersion: v1kind: Podmetadata: name: myapp-pod labels: app: myapp tier: frontend environment: production version: v1.0.0spec: containers: - name: myapp image: nginx:latestLabel Syntax Rules
Section titled “Label Syntax Rules”┌─────────────────────────────────────────────────────────────────────────────┐│ LABEL SYNTAX RULES │├─────────────────────────────────────────────────────────────────────────────┤│ ││ Valid Label Key: ││ ───────────────── ││ • Two segments: optional prefix + name, separated by '/' ││ • Prefix is optional, name is required ││ • Name segment: 1-63 characters ││ • Can contain: alphanumeric, '-', '_', '.' ││ • Must start/end with alphanumeric ││ ││ Examples: ││ ┌────────────────────────────────────────────────────────────────────┐ ││ │ app ✓ Valid │ ││ │ App ✓ Valid │ ││ │ app.myapp ✓ Valid │ ││ │ app-name ✓ Valid │ ││ │ kubernetes.io/app ✓ Valid (with prefix) │ ││ │ app_1 ✓ Valid │ ││ │ App ✓ Valid │ ││ │ (empty) ✗ Invalid │ ││ │ -app ✗ Invalid (starts with '-') │ ││ │ app@prod ✗ Invalid (contains '@') │ ││ └────────────────────────────────────────────────────────────────────┘ ││ ││ Valid Label Value: ││ ───────────────── ││ • 0-63 characters ││ • Can contain: alphanumeric, '-', '_', '.' ││ • Must start/end with alphanumeric ││ ││ Examples: ││ ┌────────────────────────────────────────────────────────────────────┐ ││ │ production ✓ Valid │ ││ │ v1.0.0 ✓ Valid │ ││ │ v1.0 ✓ Valid │ ││ │ my-app-v2 ✓ Valid │ ││ │ (empty) ✓ Valid (but not recommended) │ ││ │ -invalid ✗ Invalid │ ││ └────────────────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────────┘Using Labels
Section titled “Using Labels”Adding Labels to Objects
Section titled “Adding Labels to Objects”# Create pod with labelskubectl run myapp --image=nginx --labels="app=myapp,tier=frontend"
# Add labels to existing podkubectl label pods myapp-pod environment=production
# Add labels to nodeskubectl label nodes node-01 disktype=ssd
# Add labels to namespaceskubectl label namespace production env=prodManaging Labels
Section titled “Managing Labels”# View labelskubectl get pods --show-labels
# Label pods with specific labelskubectl get pods -L app,tier
# Update a labelkubectl label pods myapp-pod tier=backend --overwrite
# Remove a labelkubectl label pods myapp-pod tier-
# Filter by labelkubectl get pods -l app=myappkubectl get pods -l 'app in (myapp, api)'kubectl get pods -l tier=frontend,tier=backendLabel Selectors
Section titled “Label Selectors”Equality-Based Selectors
Section titled “Equality-Based Selectors”# Equals (= or ==)kubectl get pods -l app=myappkubectl get pods -l app==myapp
# Not Equals (!=)kubectl get pods -l tier!=frontendSet-Based Selectors
Section titled “Set-Based Selectors”# Inkubectl get pods -l 'app in (myapp, api)'
# Not Inkubectl get pods -l 'tier notin (frontend, backend)'
# Existskubectl get pods -l app
# Not Existskubectl get pods -l '!app'
# Combinationkubectl get pods -l 'app in (myapp, api),environment=production'Selectors in Resources
Section titled “Selectors in Resources”# ReplicaSet selectorapiVersion: apps/v1kind: ReplicaSetmetadata: name: myapp-replicasetspec: selector: matchLabels: app: myapp matchExpressions: - key: tier operator: In values: - frontend - backend
---# Service selectorapiVersion: v1kind: Servicemetadata: name: myapp-servicespec: selector: app: myapp ports: - port: 80 targetPort: 8080Selector Visual
Section titled “Selector Visual”┌─────────────────────────────────────────────────────────────────────────────┐│ LABEL SELECTOR EXAMPLES │├─────────────────────────────────────────────────────────────────────────────┤│ ││ ┌─────────────────────────────────────────────────────────────────┐ ││ │ LABELED OBJECTS │ ││ │ │ ││ │ Pod1: {app: myapp, tier: frontend, env: prod} │ ││ │ Pod2: {app: myapp, tier: backend, env: prod} │ ││ │ Pod3: {app: api, tier: backend, env: staging} │ ││ │ Pod4: {app: myapp, tier: frontend, env: staging} │ ││ │ │ ││ └─────────────────────────────────────────────────────────────────┘ ││ ││ Selector Examples: ││ ──────────────── ││ ││ app=myapp ││ ┌─────────────────────────────────────────────────────────────────┐ ││ │ Selected: Pod1, Pod2, Pod4 │ ││ └─────────────────────────────────────────────────────────────────┘ ││ ││ tier=frontend ││ ┌─────────────────────────────────────────────────────────────────┐ ││ │ Selected: Pod1, Pod4 │ ││ └─────────────────────────────────────────────────────────────────┘ ││ ││ app in (myapp, api), env=prod ││ ┌─────────────────────────────────────────────────────────────────┐ ││ │ Selected: Pod1, Pod2 │ ││ └─────────────────────────────────────────────────────────────────┘ ││ ││ tier notin (frontend) ││ ┌─────────────────────────────────────────────────────────────────┐ ││ │ Selected: Pod2, Pod3 │ ││ └─────────────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────────┘Annotations
Section titled “Annotations”What are Annotations?
Section titled “What are Annotations?”Annotations are similar to labels but are intended for non-identifying metadata. They are used to attach arbitrary metadata that can be used by tools, libraries, or for documentation purposes.
# Pod with annotationsapiVersion: v1kind: Podmetadata: name: myapp-pod annotations: description: "Production web server for myapp" maintainer: "team@example.com" kubernetes.io/change-cause: "Update to version 2.0" prometheus.io/scrape: "true" prometheus.io/port: "8080"spec: containers: - name: myapp image: nginx:latestLabels vs Annotations
Section titled “Labels vs Annotations”┌─────────────────────────────────────────────────────────────────────────────┐│ LABELS VS ANNOTATIONS │├─────────────────────────────────────────────────────────────────────────────┤│ ││ Feature │ Labels │ Annotations ││ ────────────────┼────────────────────┼─────────────────── ││ Purpose │ Identify & select │ Attach metadata ││ Used by K8s │ Yes (selectors) │ No ││ Queryable │ Yes │ Usually not ││ Character limit│ 63 char │ No limit ││ Recommended │ Key info │ Additional info ││ Use cases │ • app name │ • Description ││ │ • tier │ • Maintainer info ││ │ • environment │ • Build info ││ │ • version │ • Links to docs ││ ││ Examples: ││ ┌────────────────────────────────────────────────────────────────────┐ ││ │ Labels: │ ││ │ app: myapp, tier: frontend, version: v1.0 │ ││ │ │ ││ │ Annotations: │ ││ │ description: "Frontend web server for customer-facing app" │ ││ │ build: "jenkins-build-1234" │ ││ │ kubernetes.io/ingress.class: "nginx" │ ││ └────────────────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────────┘Hands-on Lab
Section titled “Hands-on Lab”Lab: Working with Labels and Selectors
Section titled “Lab: Working with Labels and Selectors”Prerequisites
Section titled “Prerequisites”- A running Kubernetes cluster
Lab Steps
Section titled “Lab Steps”# Step 1: Create pods with labelskubectl run frontend --image=nginx --labels="app=myapp,tier=frontend,environment=dev"kubectl run backend --image=nginx --labels="app=myapp,tier=backend,environment=dev"kubectl run cache --image=redis --labels="app=myapp,tier=cache,environment=dev"
# Step 2: List pods with labelskubectl get pods --show-labels
# Step 3: Filter by labelskubectl get pods -l app=myappkubectl get pods -l tier=frontendkubectl get pods -l 'app in (myapp, api)'kubectl get pods -l 'environment=dev,tier=frontend'
# Step 4: Add labels to existing podkubectl label pods backend environment=production
# Step 5: Verify label changekubectl get pods -l environment
# Step 6: Use labels with servicescat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata: name: myapp-servicespec: selector: app: myapp ports: - port: 80 targetPort: 80EOF
# Step 7: Use labels with deploymentscat <<EOF | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata: name: myapp-deploymentspec: selector: matchLabels: app: myapp replicas: 3 template: metadata: labels: app: myapp tier: frontend spec: containers: - name: nginx image: nginx:latestEOF
# Step 8: Node labels (for scheduling)kubectl label nodes <node-name> disktype=ssd
# Step 9: Add annotationskubectl annotate pod myapp-pod description="Production API server"
# Step 10: View annotationskubectl describe pod myapp-pod | grep -A 10 Annotations
# Step 11: Clean upkubectl delete pod frontend backend cachekubectl delete service myapp-servicekubectl delete deployment myapp-deploymentSummary
Section titled “Summary”Key Takeaways
Section titled “Key Takeaways”- Labels - Key-value pairs for identification and selection
- Selectors - Filter objects by label criteria
- Equality-based - =, ==, !=
- Set-based - in, notin, exists, !
- Annotations - Non-identifying metadata
Quick Reference
Section titled “Quick Reference”# Add labelskubectl label pods <pod> key=value
# Remove labelkubectl label pods <pod> key-
# Filter by labelkubectl get pods -l key=value
# Add annotationkubectl annotate pod <pod> key=value
# Get with labelskubectl get pods -L key1,key2kubectl get pods --show-labelsWhat’s Next?
Section titled “What’s Next?”This completes the Kubernetes Fundamentals section. You now have a solid understanding of:
- Kubernetes Introduction
- Pods
- Deployments
- Services
- Installation
- ReplicaSets
- ConfigMaps and Secrets
- Storage
- Namespaces
- Labels and Selectors
Continue to Kubernetes Advanced topics (Chapter 26-32):
- Ingress Controllers
- Horizontal Pod Autoscaling
- StatefulSets
- Network Policies
- RBAC
- Helm
- Operators