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:
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
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:
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"
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:
Key takeaways¶
- Use YAML manifests to declaratively define pod configurations.
- Leverage node selectors and affinity rules to control scheduling.
- Manage pods with
kubectlcommands for monitoring, debugging, and lifecycle control. - Understand pod states to troubleshoot scheduling or runtime issues.