Skip to content

Pod Management

Kubernetes manages pods through a combination of declarative manifests, scheduling rules, and operational commands. This section covers how to create, schedule, and manage pods using YAML configurations and kubectl tools.


Pod Lifecycle and States

Kubernetes pods transition through several states:
- Pending: The pod has been created but not yet scheduled (e.g., due to resource constraints).
- Running: The pod has been assigned to a node and all containers are running.
- Succeeded/Failed: The pod completed successfully or failed (e.g., due to container errors).
- Unknown: The status cannot be determined (e.g., due to network issues).

Use kubectl get pods to check the current state:

kubectl get pods --watch


Creating Pods with YAML Manifests

YAML manifests define pod specifications. A minimal example:

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80
Apply the manifest with:
kubectl apply -f nginx-pod.yaml

Key fields:
- metadata.name: Unique pod identifier.
- spec.containers: List of containers with image, ports, and resources.
- spec.nodeSelector: Optional rules to schedule the pod on specific nodes.


Scheduling and Affinity Rules

Kubernetes schedules pods based on node resources and affinity rules.

Node Selectors

Assign pods to specific nodes:

spec:
  nodeSelector:
    role: app-server
Ensure the node has the label role=app-server via kubectl label nodes <node-name> role=app-server.

Affinity and Anti-Affinity

Use affinity rules for co-location or anti-colocation:

spec:
  affinity:
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: app
            value: database
            operator: In
        topologyKey: "kubernetes.io/hostname"
This ensures the pod runs on the same node as another pod labeled app=database.


Managing Pods with kubectl

Use kubectl to inspect, debug, and control pods:

Inspecting Pods

kubectl describe pod nginx-pod
kubectl logs nginx-pod  # View container logs
kubectl exec -it nginx-pod -- sh  # Interactive shell in the container

Updating and Deleting Pods

Update a pod by modifying the YAML manifest and reapplying it. Delete a pod:

kubectl delete pod nginx-pod


Key takeaways

  • Use YAML manifests to declaratively define pod configurations.
  • Leverage node selectors and affinity rules to control scheduling.
  • Manage pods with kubectl commands for monitoring, debugging, and lifecycle control.
  • Understand pod states to troubleshoot scheduling or runtime issues.