Kubernetes Hour 1: Architecture and Core Objects
- Explain how Kubernetes works using “desired state + control loop (reconcile loop),” and decide whether a given scenario needs K8s.
- Draw the architecture of the control plane (kube-apiserver / etcd / scheduler / controller-manager) and nodes (kubelet / kube-proxy / containerd / CNI), and explain why “all components talk only to the apiserver.”
- Use kubectl fluently: kubeconfig contexts,
explain,-o jsonpath/custom-columns/kyaml,--dry-run,diff,-v=8. - Walk through the full journey of one
kubectl apply: authentication → authorization → admission → etcd → controllers → scheduling → kubelet → CRI → CNI → EndpointSlice. - Deploy, diagnose, upgrade, and roll back a 3-replica Deployment, and expose it with a Service (ClusterIP / NodePort). Independently diagnose Pending, ImagePullBackOff, CrashLoopBackOff, and a Service with no endpoints.
Hour 1 Timetable
| # | Time | Module | Core content | Animation / interactive | Lab (kind on Azure VM) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup | kubectl 1.37, kind v0.33.0, 3-node cluster lab, completion and aliases | — | kind create cluster, get nodes -o wide |
| 1 | 00–06 | Why K8s | Imperative vs declarative, desired and actual state, control loops, self-healing; comparison with Compose/Swarm/ACA/ECS | Control loop: delete a Pod → watch → recreate | Delete a Pod and watch it self-heal |
| 2 | 06–14 | Cluster architecture | apiserver, etcd (Raft), scheduler, controller-manager, kubelet, kube-proxy, containerd, CNI, CoreDNS | Hub-and-spoke: who watches whom | crictl ps, static Pods, /readyz?verbose |
| 3 | 14–21 | kubectl and the API object model | kubeconfig, GVK/GVR, explain, output formats, dry-run, diff, REST | YAML field explainer + line-by-line reading of -v=8 | kubectl proxy + curl API |
| 4 | 21–29 | Pod | Shared namespaces, pause, multi-container Pods, init containers, native sidecars, phase and container states | Clickable Pod lifecycle state machine | podinfo + trigger ImagePullBackOff / CrashLoopBackOff |
| 5 | 29–36 | The full journey of kubectl apply | SSA vs CSA, authentication/authorization/admission, etcd, controller chain, scheduling, CRI, CNI | Core animation: 14 real API calls | apply --server-side, events, managedFields |
| 6 | 36–42 | Namespace · Label · Selector | Scope, recommended labels, equality and set-based selectors, field selectors, annotations | Change a label to detach a Pod from its RS | -l, -L, label, --field-selector |
| 7 | 42–51 | Deployment and ReplicaSet | pod-template-hash, RollingUpdate/Recreate, rollout commands, change-cause | Rolling update simulator (adjustable maxSurge/maxUnavailable) | 6.16.0 → 6.17.0, stuck on a bad image, undo |
| 8 | 51–60 | Service basics and basic troubleshooting | ClusterIP/NodePort, EndpointSlice, DNS, port/targetPort/nodePort | Service traffic path + troubleshooting decision tree | expose, port-forward, busybox debugging |
| — | After class | Cheat sheet · Capstone lab | shop/api declarative deployment → upgrade → self-healing → rollback → troubleshooting | 12-question final quiz | Capstone lab (keep the cluster for hour 2) |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain declarative and control loops | ✓ | · | · | · | ✓ | · | ✓ | · | kubectl get -w | Self-healing after deleting a Pod |
| Identify control plane and node components | · | ✓ | · | · | ✓ | · | · | · | crictl ps, get --raw /readyz | Enter a kind node |
| Manage kubeconfig and contexts | · | · | ✓ | · | · | ✓ | · | · | config use-context | Switch the default namespace |
| Read API objects and GVK/GVR | · | · | ✓ | · | ✓ | · | · | · | explain, api-resources | kubectl proxy + curl |
| Generate and compare manifests | · | · | ✓ | · | ✓ | · | ✓ | · | --dry-run=client -o yaml, diff | Capstone lab |
| Pod design and lifecycle diagnosis | · | · | · | ✓ | · | · | · | ✓ | describe, logs --previous, debug | ImagePullBackOff / CrashLoopBackOff |
| Understand the full apply path | · | ✓ | · | · | ✓ | · | · | · | apply --server-side, -v=8 | events timeline |
| Labels, selectors and namespaces | · | · | · | · | · | ✓ | ✓ | ✓ | -l, -L, label --overwrite | Detach a Pod from its RS |
| Rolling releases and rollbacks | · | · | · | · | · | · | ✓ | · | rollout status/undo | 6.16.0 → 6.17.0 |
| Exposing a Service and basic troubleshooting | · | · | · | · | ✓ | ✓ | · | ✓ | get endpointslices, run tmp --rm -it | NodePort + DNS |
Topics excluded from this hour (time limits; covered in later hours)
| Topic | Why it is not covered this hour | Where to learn it |
|---|---|---|
| Probes (liveness/readiness/startup), requests/limits, QoS, ConfigMap/Secret, StatefulSet, Job/CronJob, DaemonSet details | Belongs to “making workloads production-ready” | Hour 2 |
| LoadBalancer, Gateway API, Ingress, NetworkPolicy, CNI deep dive, kube-proxy nftables rule details | Requires Service basics first | Hour 3 |
| PV/PVC/StorageClass, CSI, backup and restore | Persistence gets its own hour | Hour 4 |
| Writing RBAC, ServiceAccount, Pod Security Admission, writing admission policies | This hour only touches authentication, authorization, and admission in the apply journey | Hour 5 |
| HPA/VPA, observability, PDB and priority, cluster upgrades and maintenance | Production operations | Hour 6 |
| Helm, Kustomize, GitOps, production AKS clusters | Delivery tools and managed platforms each have their own courses | Overview in hour 6; for more depth, see the Helm, GitOps and Argo CD, and AKS courses |
| Building clusters with kubeadm, etcd operations, certificate rotation | On a managed cluster (AKS), the platform handles this; CKA track | Official docs: kubeadm |
How to use this course material
Theory · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Voice · Video. Suggested order: theory → animation → lab → quiz. Review troubleshooting and production cases after class.
A module counts toward your progress when your quiz score is ≥ 70% or when you click “Mark this module complete.” Progress is saved in this browser's localStorage (in private mode, it is lost on refresh).
The “Voice” page reads the narration script aloud using the browser's built-in Web Speech API (en-US). English terms are also read in en-US. If no English voice pack is installed, a notice appears, and the narration script can still be read or passed to a TTS tool.
kindest/node:v1.37.0. kubectl and the apiserver may differ by one minor version, so kubectl 1.37 can manage clusters from 1.36 to 1.38. Changes in v1.37 relevant to this hour: kubectl get -o kyaml goes GA; kube-proxy's ipvs mode is deprecated (nftables is recommended); kubectl run -f is deprecated; kubelet does not start by default on cgroup v1 nodes (failCgroupV1 has defaulted to true since v1.35).docker run starts a container through containerd → shim → runc. Kubernetes nodes also use containerd + runc. The difference is who starts the creation: the kubelet (through CRI gRPC) replaces dockerd, and it continuously creates and repairs containers based on the desired state in the API.Module 0 · Environment setup (complete before class)
lab cluster with 1 control plane node and 2 worker nodes- The lab VM from the Docker course, or a new one: Ubuntu 24.04 LTS,
Standard_D4s_v5(4 vCPU / 16 GiB), resource grouprg-k8s-lab, regioncanadacentral. - Docker Engine 29.x is installed on the VM, and the current user is in the
dockergroup (docker psworks without sudo). - Each kind “node” is a Docker container (running systemd + containerd + kubelet inside), so a 3-node cluster uses about 2–3 GiB of memory.
Step 1: Create the lab VM (if needed)
RG=rg-k8s-lab LOC=canadacentral az group create -n $RG -l $LOC az vm create -g $RG -n vm-k8s \ --image Ubuntu2404 \ --size Standard_D4s_v5 \ --admin-username azureuser \ --generate-ssh-keys \ --public-ip-sku Standard ssh azureuser@$(az vm show -d -g $RG -n vm-k8s --query publicIps -o tsv)
az vm deallocate -g rg-k8s-lab -n vm-k8s to stop compute billing. After all 6 hours of the course, run az group delete -n rg-k8s-lab --yes --no-wait. For Docker installation steps, see Module 0 of the Docker course.Step 2: Kernel parameters (a known issue with multi-node kind)
# Known kind issue: with several nodes, "too many open files" can appear; raise the inotify limits sudo sysctl fs.inotify.max_user_watches=524288 sudo sysctl fs.inotify.max_user_instances=512 echo -e "fs.inotify.max_user_watches=524288\nfs.inotify.max_user_instances=512" | sudo tee /etc/sysctl.d/99-kind.conf # Confirm cgroup v2 (default on Ubuntu 24.04); kubelet v1.35+ refuses to start on cgroup v1 by default stat -fc %T /sys/fs/cgroup/
cgroup2fs
Step 3: Install kubectl 1.37 (official apt repository at pkgs.k8s.io)
sudo apt-get update sudo apt-get install -y apt-transport-https ca-certificates curl gnupg sudo mkdir -p -m 755 /etc/apt/keyrings curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.37/deb/Release.key \ | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg sudo chmod 644 /etc/apt/keyrings/kubernetes-apt-keyring.gpg echo 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.37/deb/ /' \ | sudo tee /etc/apt/sources.list.d/kubernetes.list sudo chmod 644 /etc/apt/sources.list.d/kubernetes.list sudo apt-get update sudo apt-get install -y kubectl kubectl version --client
Client Version: v1.37.1 Kustomize Version: v5.x.x
The pkgs.k8s.io repositories are split by minor version: the v1.37 in the URL limits you to 1.37.x. To upgrade to 1.38, change the repository URL.
Alternative: download the binary directly (if apt is not available)
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256" echo "$(cat kubectl.sha256) kubectl" | sha256sum --check sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
kubectl: OK
stable.txt always points to the latest stable release. To pin 1.37, replace $(curl …stable.txt) with v1.37.1.
Step 4: Install kind v0.33.0
curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.33.0/kind-linux-amd64 chmod +x ./kind sudo mv ./kind /usr/local/bin/kind kind version
kind v0.33.0 go1.2x.x linux/amd64
Step 5: Write the cluster config kind-lab.yaml
mkdir -p ~/k8slab && cd ~/k8slab
cat > kind-lab.yaml <<'EOF'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: lab
nodes:
- role: control-plane
image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
extraPortMappings: # Map NodePort 30080 to 127.0.0.1:30080 on the VM (used in Module 8 and the capstone lab)
- containerPort: 30080
hostPort: 30080
listenAddress: "127.0.0.1"
protocol: TCP
- role: worker
image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
- role: worker
image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
EOF
@sha256: digest reference, because the same tag can be rebuilt. Node images built by different kind versions are not guaranteed to be compatible. This is the same principle as “reference digests in production deployments” in the Docker course.Step 6: Create the cluster
kind create cluster --name lab --config kind-lab.yaml
Creating cluster "lab" ... ✓ Ensuring node image (kindest/node:v1.37.0) 🖼 ✓ Preparing nodes 📦 📦 📦 ✓ Writing configuration 📜 ✓ Starting control-plane 🕹️ ✓ Installing CNI 🔌 ✓ Installing StorageClass 💾 ✓ Joining worker nodes 🚜 Set kubectl context to "kind-lab" You can now use your cluster with: kubectl cluster-info --context kind-lab
kind uses kubeadm internally to bootstrap the control plane, then runs kubeadm join for the two workers. The CNI is kindnet, which ships with kind, and the StorageClass is local-path-provisioner. The kubeconfig is written to ~/.kube/config, and the context is named kind-lab.
Step 7: Completion and aliases (strongly recommended)
sudo apt-get install -y bash-completion echo 'source <(kubectl completion bash)' >> ~/.bashrc echo 'alias k=kubectl' >> ~/.bashrc echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc echo 'export do="--dry-run=client -o yaml"' >> ~/.bashrc # Usage: k create deploy x --image=y $do source ~/.bashrc k get no
Step 8: Verify the cluster
kubectl cluster-info
kubectl get nodes -o wide
docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Ports}}'
Kubernetes control plane is running at https://127.0.0.1:41234 CoreDNS is running at https://127.0.0.1:41234/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME lab-control-plane Ready control-plane 92s v1.37.0 172.18.0.4 <none> Debian GNU/Linux 12 (bookworm) 6.8.0-1017-azure containerd://2.x.x lab-worker Ready <none> 71s v1.37.0 172.18.0.2 <none> Debian GNU/Linux 12 (bookworm) 6.8.0-1017-azure containerd://2.x.x lab-worker2 Ready <none> 71s v1.37.0 172.18.0.3 <none> Debian GNU/Linux 12 (bookworm) 6.8.0-1017-azure containerd://2.x.x NAMES IMAGE PORTS lab-control-plane kindest/node:v1.37.0 127.0.0.1:30080->30080/tcp, 127.0.0.1:41234->6443/tcp lab-worker kindest/node:v1.37.0 lab-worker2 kindest/node:v1.37.0
Note: KERNEL-VERSION is the VM's kernel. kind nodes are just containers, so they share the host kernel. OS-IMAGE is the base distribution of the node image; check your actual output. The apiserver's port 6443 is mapped to a random port on 127.0.0.1 on the VM.
Alternatives (if you do not have an Azure VM)
| Option | Notes | Cost |
|---|---|---|
| Docker Desktop built-in Kubernetes | Settings → Kubernetes → Enable. Newer versions offer a multi-node cluster in kind mode. Context name: docker-desktop. Some labs (docker exec lab-control-plane …) need the matching node name instead | Free for personal use; large enterprises need a paid subscription |
| minikube | minikube start --nodes 3 --kubernetes-version=v1.37.0; node names are minikube, minikube-m02…; includes addons (metrics-server, ingress) | Free |
| AKS | az aks create -g rg-k8s-lab -n aks-lab --node-count 2 --generate-ssh-keys; the control plane is managed and not visible (the crictl and static Pod labs in Module 2 cannot be done) | The Free tier control plane is free; you pay for the node VMs. Run az group delete when you are finished. |
Module 1 · Why Kubernetes: declarative model and control loops
- Distinguish imperative and declarative operations, and explain why the declarative approach suits large-scale operations and GitOps.
- Explain desired state (
spec) and actual state (status), and the controller's observe → diff → act loop. - Explain who actually performs “self-healing” and which API mechanism (watch / informer) triggers it.
- Make a justified choice between Compose, Swarm, Azure Container Apps, ECS, and Kubernetes, and know when you should not use K8s.
What: what Kubernetes is
Kubernetes is an API-centric, declarative container orchestration system. You write the desired state as API objects and submit them to the kube-apiserver. For example: “the shop namespace should have 3 podinfo 6.17.0 replicas, reachable through a Service named api.” The objects are persisted in etcd. A set of independent controllers continuously watches these objects and adjusts the real world (containers on nodes, network rules, cloud resources) to match the desired state.
| Aspect | Imperative | Declarative |
|---|---|---|
| How you express it | “Do these steps”: docker run ×3, kubectl scale --replicas=3 | “This is the result I want”: replicas: 3 in YAML, applied with kubectl apply -f |
| After a failure | The script stops, the state is unknown, and someone has to fix it by hand | The controller retries automatically on its next loop until the state converges |
| Drift | Someone changes it by hand, and nobody knows | The controller pulls fields such as the replica count back to the desired value; kubectl diff shows the difference |
| Auditable and reproducible | Depends on command history | Manifests go into Git → code review → GitOps (hour 6) |
| Idempotent | Repeated runs may create duplicates | Repeated apply has no side effects |
Why: why control loops are needed
In distributed systems, failure is normal: nodes go down, containers hit OOM, networks partition, and rollouts get interrupted. An imperative script is only correct at the moment it runs. A control loop constantly compares and corrects. Every Kubernetes controller follows the same pattern:
Through the apiserver's LIST + WATCH (client-go informer), the controller caches the objects it cares about locally and receives ADDED / MODIFIED / DELETED events.
Compare
spec (desired) with what is observed. For example, a ReplicaSet expects 3 Pods, but its selector matches 2.Call the apiserver to create, delete, or update objects (for example,
POST /api/v1/namespaces/shop/pods), and write the observed result back to status. Then return to ①.Key point: controllers do not operate containers directly. The ReplicaSet controller only creates Pod objects. The scheduler only writes a nodeName onto a Pod. The kubelet sees Pods assigned to its own node and then uses CRI to have containerd start the containers. Each layer handles only its own part of convergence and is decoupled from the others through API objects. This is why K8s is extensible (CRDs + custom controllers = Operators).
How: how self-healing happens
- Container crash: the kubelet restarts the container on the same node according to
restartPolicy, with exponential backoff (this is CrashLoopBackOff). - Pod deleted or evicted: the ReplicaSet controller notices fewer matching Pods and creates a new Pod (new name, new IP, possibly on another node).
- Node lost: after the node's heartbeat (Lease) times out, the node lifecycle controller marks the node NotReady and adds a taint. The Pods on that node are then evicted, and the RS recreates them on other nodes.
- Service backend changes: the EndpointSlice controller updates the backend list based on Pod readiness, and kube-proxy then syncs the forwarding rules on the node.
When: when to use K8s and when not to
| Option | Best for | Main costs / limits |
|---|---|---|
| Docker Compose | Single-machine development, integration testing, small single-host services | No cross-host scheduling; failed health checks do not trigger automatic replacement; no rolling updates |
| Docker Swarm | Small teams already on Swarm that need simple multi-host orchestration | A much smaller ecosystem and community than K8s, and few new features |
| Azure Container Apps (ACA) | HTTP/event-driven microservices, scale-to-zero, teams that do not want to manage clusters | Built on managed K8s + KEDA + Envoy, but does not expose the K8s API; advanced networking and scheduling are limited |
| AWS ECS | Deeply tied to AWS, and prefers native AWS IAM/ALB integration | Proprietary API with high migration cost; ecosystem tools (Helm/Operators) are not available |
| Kubernetes (AKS/EKS/GKE/self-managed) | Multi-team platforms, dozens of services or more, portability needs, Operator ecosystem, fine-grained scheduling and policy | Learning curve, operational complexity, need for a platform team; the control plane and nodes carry fixed costs |
kubectl rollout status to check. (4) “Declarative means using YAML.” YAML is just the format. The real idea is submitting a desired state and letting controllers converge on it.Figure 1-1: Control loop (reconcile loop)
Figure 1-2: Imperative vs declarative workflow
Step-by-step animation: manually delete a Pod, and see how the ReplicaSet controller “brings it back”
Scenario: the shop/api Deployment expects 3 replicas. You run kubectl delete pod api-7c6b9f8d5d-x2k4p. Watch which component does each step and which API/watch event it reacts to.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl create deployment | Imperative create (good for quick experiments or generating YAML) | --image --replicas --port --dry-run=client -o yaml |
kubectl apply -f | Declarative submission of desired state | --server-side, -k (Kustomize), --prune (use with caution) |
kubectl get -w | Continuously watch object changes (under the hood, it uses WATCH) | --output-watch-events shows ADDED/MODIFIED/DELETED |
kubectl diff -f | Preview the differences between the desired state and the cluster's current state | Exit code 1 means differences were found; suitable for CI |
kubectl scale | Change the replica count imperatively | Causes drift from the declarations in Git; avoid in production |
kubectl create namespace shop kubectl -n shop create deployment api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=3 --port=9898 kubectl -n shop get deploy,rs,pods
deployment.apps/api created NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/api 3/3 3 3 20s NAME DESIRED CURRENT READY AGE replicaset.apps/api-6d9c7b8f6d 3 3 3 20s NAME READY STATUS RESTARTS AGE pod/api-6d9c7b8f6d-7xk2m 1/1 Running 0 20s pod/api-6d9c7b8f6d-h4q9d 1/1 Running 0 20s pod/api-6d9c7b8f6d-zp6tn 1/1 Running 0 20s
kubectl -n shop get pods --watch --output-watch-events
EVENT NAME READY STATUS RESTARTS AGE ADDED api-6d9c7b8f6d-7xk2m 1/1 Running 0 2m ... MODIFIED api-6d9c7b8f6d-7xk2m 1/1 Terminating 0 2m ADDED api-6d9c7b8f6d-q8w5r 0/1 Pending 0 0s MODIFIED api-6d9c7b8f6d-q8w5r 0/1 ContainerCreating 0 0s MODIFIED api-6d9c7b8f6d-q8w5r 1/1 Running 0 2s DELETED api-6d9c7b8f6d-7xk2m 0/1 Completed 0 2m
- How to verify: In
kubectl -n shop get rs, DESIRED/CURRENT/READY is back to 3/3/3. - Common mistake: you run
kubectl scaleby hand, and the next CI run ofapplychanges it back. This is declarative “drift correction” working as designed, not a bug. - Production use: run
kubectl diffas a PR check to show which fields in the cluster each merge would change.
Lab 1: See the control loop in action (about 4 min)
lab, namespace shop. If you already created api on the previous page, skip the next step.kubectl create namespace shop --dry-run=client -o yaml | kubectl apply -f - kubectl -n shop create deployment api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=3 --port=9898 kubectl -n shop rollout status deploy/api
deployment "api" successfully rolled out
kubectl -n shop get pods -o wide -w
kubectl -n shop delete pod $(kubectl -n shop get pod -o name | head -1 | cut -d/ -f2) kubectl -n shop delete pods --all --wait=false kubectl -n shop get rs
In terminal A, notice that the new Pod has a different name suffix and IP, and may be scheduled to another worker. The RS name (api-6d9c7b8f6d) stays the same.
kubectl -n shop scale rs $(kubectl -n shop get rs -o name | head -1 | cut -d/ -f2) --replicas=1 sleep 3; kubectl -n shop get rs,pods
NAME DESIRED CURRENT READY AGE replicaset.apps/api-6d9c7b8f6d 3 3 3 4m
The Deployment controller notices that the replica count of the RS it owns does not match the Deployment's spec.replicas, and immediately sets it back to 3. The higher-level controller corrects the lower one.
kubectl -n shop get events --sort-by=.lastTimestamp | tail -15
Normal SuccessfulCreate replicaset/api-6d9c7b8f6d Created pod: api-6d9c7b8f6d-q8w5r Normal Scheduled pod/api-6d9c7b8f6d-q8w5r Successfully assigned shop/api-6d9c7b8f6d-q8w5r to lab-worker2 Normal Pulled pod/api-6d9c7b8f6d-q8w5r Container image "ghcr.io/stefanprodan/podinfo:6.17.0" already present on machine Normal ScalingReplicaSet deployment/api Scaled up replica set api-6d9c7b8f6d from 1 to 3
kubectl -n shop delete deploy api (keep the shop namespace for later modules).Case 1: Automatic recovery time when a node fails
Problem: An AKS node lost contact during host maintenance. The business team complains: “K8s is supposed to self-heal. Why did the Pods take 5 minutes to move?”
Approach: Understand the two delays. (1) The node lifecycle controller waits for the node's Lease to time out (--node-monitor-grace-period, default is tens of seconds; check the kube-controller-manager docs for your version for the exact value), then marks the node NotReady and adds the node.kubernetes.io/unreachable taint. (2) By default, Pods tolerate that taint with tolerationSeconds: 300 (injected by the DefaultTolerationSeconds admission plugin), so they are evicted only after 5 minutes. For critical services, you can shorten the toleration time. Also, always keep ≥2 replicas plus topology spread so a single node failure does not affect availability.
tolerations: - key: node.kubernetes.io/unreachable operator: Exists effect: NoExecute tolerationSeconds: 60 - key: node.kubernetes.io/not-ready operator: Exists effect: NoExecute tolerationSeconds: 60
Limits: If the time is too short, brief network blips can trigger unnecessary mass rebuilds. StatefulSet Pods are not automatically recreated with the same name elsewhere (see hour 4).
Case 2: A manual hotfix gets “automatically reverted”
Problem: The on-call engineer used kubectl edit deploy to change the image to a hotfix version. Half an hour later, the GitOps tool (Argo CD/Flux) changed it back, and the failure came back.
Approach: In a declarative system, Git is the single source of truth. Emergency fixes should use the fast path: commit to Git, and let automatic sync apply it. If you must make a temporary manual change, first pause automatic sync for that application in the GitOps tool.
Limits: This needs team process support. The actual GitOps setup is covered in hour 6.
Case 3: Making the right call not to use K8s
Problem: The team has one Python API and one Postgres database, with 3 developers, and is asked to “adopt K8s.”
Approach: Choose Azure Container Apps (or App Service) + Azure Database for PostgreSQL. They still run containers and support revisions and traffic splitting, with zero cluster operations. When the number of services and team size grow, and you need Operators or custom scheduling, move to AKS. The container images can be reused as they are.
Common symptoms and troubleshooting
You deleted a Pod, but it “comes back” and you cannot get rid of it
Cause: The Pod is managed by a ReplicaSet (and in turn by a Deployment). Deleting the Pod only makes the actual state differ from the desired state, so the controller recreates it.
kubectl -n shop get pod POD -o jsonpath='{.metadata.ownerReferences[*].kind}/{.metadata.ownerReferences[*].name}{"\n"}'
# Output: ReplicaSet/api-6d9c7b8f6d → find its Deployment
kubectl -n shop delete deploy api # Delete the parent object; this cascades to the RS and Pods
# Or scale it to 0 temporarily: kubectl -n shop scale deploy api --replicas=0The replica count you changed with kubectl scale was changed back after a while
Cause: (1) You changed the RS, and the Deployment corrected it. (2) A GitOps tool or CI is applying manifests on a schedule. (3) An HPA (hour 6) is in place and keeps setting replicas.
kubectl -n shop get hpa
kubectl -n shop get deploy api -o jsonpath='{.metadata.managedFields[*].manager}{"\n"}' # Who is managing this objectapply succeeded, but READY stays at 0/3
Cause: apply only means the object was written to etcd. Scheduling, image pulls, and startup can all fail afterward.
kubectl -n shop rollout status deploy/api --timeout=60s kubectl -n shop get pods kubectl -n shop describe pod POD | sed -n '/Events/,$p'
Use the STATUS (Pending / ImagePullBackOff / CrashLoopBackOff) to follow the troubleshooting paths in Modules 4 and 8.
1. Use one command to continuously watch Pod changes in the shop namespace, and show the event type (ADDED/MODIFIED/DELETED).
kubectl -n shop get pods -w --output-watch-events
2. Find the kind and name of the direct owner of Pod api-6d9c7b8f6d-7xk2m.
kubectl -n shop get pod api-6d9c7b8f6d-7xk2m -o jsonpath='{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}{"\n"}'Your boss asks: “We run our 6 microservices with Docker Compose on one VM. Sometimes a container dies and nobody knows. Should we go straight to AKS?” Give your analysis.
First, identify the real pain points: no self-healing or alerting, and a single VM as a single point of failure. Options: (1) Short term: add restart: unless-stopped to Compose and use external monitoring. This is the lowest cost. (2) Medium term: Azure Container Apps, which gives you self-healing, revisions, managed ingress, and scale-to-zero, with no cluster operations. (3) If the number of services grows later and you need Operators, multi-team isolation, fine-grained network policies, or portability, move to AKS, with a platform owner and an upgrade process in place. The answer depends on team size and operational investment, not on “K8s is more advanced.”
Verified teaching videos
Official docs
Video storyboard script (can be given to a video generation tool)
This course material cannot generate video or MP3 files directly, so it provides the storyboard and narration script.
Visual: 3 a.m. An engineer SSHs into several VMs and runs docker run by hand. Alerts keep firing.
Narration: “If every failure needs a person to fix it, the bigger the system gets, the harder it is to sleep at night.”
Visual: A YAML file with replicas: 3 is submitted to the apiserver, and an icon moves into etcd.
Narration: “Kubernetes takes a different approach. You declare the result you want, such as three replicas, and the system makes it happen and keeps it that way.”
Visual: A circular arrow labeled observe, compare, act; the ReplicaSet controller watches three Pods.
Narration: “Every controller runs the same loop: observe reality, compare it with the desired state, then act.”
Visual: A Pod is removed with a red X; DELETED appears in the watch stream; the controller creates a new Pod and schedules it on another node.
Narration: “Delete a Pod, and the controller sees the difference in the watch stream and immediately creates a new one. That is self-healing.”
Visual: A comparison table: Compose, ACA, ECS, Kubernetes.
Narration: “But it is not a cure-all. When you have few services and a small team, a managed container platform is often the better choice.”
Module 2 · Cluster architecture: control plane and nodes
- Describe the roles of the 5 control plane components (kube-apiserver, etcd, kube-scheduler, kube-controller-manager, cloud-controller-manager) and the 4 types of node components (kubelet, kube-proxy, container runtime, CNI).
- Understand the hub-and-spoke design, where only the apiserver accesses etcd and all other components coordinate through apiserver watches.
- Use
crictlon a kind node to inspect containers, find the static Pod manifests, and check the apiserver health endpoints. - Know which components are hidden on managed services such as AKS, and who is responsible for them.
What: component list
| Location | Component | Responsibility | Talks to |
|---|---|---|---|
| Control plane | kube-apiserver | The single entry point for the REST API; authentication, authorization, admission, and validation; reads and writes objects to etcd; provides watch | All components → apiserver; apiserver → etcd, webhooks, kubelet (exec/logs) |
| etcd | A strongly consistent key-value store (Raft consensus) that holds all cluster state; odd-numbered members (3/5); writes succeed only while a majority is alive | Accessed only by the apiserver (mTLS) | |
| kube-scheduler | Watches Pods with an empty spec.nodeName, filters → scores → writes the node name through the pods/binding subresource | apiserver | |
| kube-controller-manager | Runs dozens of controllers in one process: Deployment, ReplicaSet, Node lifecycle, EndpointSlice, Namespace, ServiceAccount, Job, GC, and more | apiserver | |
| cloud-controller-manager | Cloud-provider controllers: nodes (cloud VM metadata), routes, and cloud load balancers for type: LoadBalancer | apiserver + cloud API (not present in kind) | |
| Each node | kubelet | Node agent: watches Pods scheduled to its node, uses CRI to have the runtime create containers, runs probes, mounts volumes, reports Node/Pod status and Lease heartbeats, and manages static Pods | apiserver; local CRI socket |
| kube-proxy | Watches Services and EndpointSlices, and programs iptables (the Linux default) or nftables (GA in v1.33, recommended) rules on the node. The ipvs mode is deprecated in v1.37 | apiserver; kernel netfilter | |
| Container runtime | containerd 2.x (or CRI-O), implements the CRI gRPC interface (RuntimeService / ImageService) and calls runc underneath | kubelet (unix socket) | |
| CNI plugin | Called by the runtime when it creates the Pod sandbox (ADD/DEL). It assigns the Pod IP and connects the Pod to the network. kind uses kindnet by default; AKS often uses Azure CNI (Cilium) | Called by containerd; may run its own DaemonSet | |
| Addons | CoreDNS, metrics-server | CoreDNS provides cluster DNS (Service name resolution). metrics-server provides resource metrics for kubectl top and HPA (the metrics.k8s.io API is GA in v1.37). kube-dns is deprecated | Runs as a regular Deployment |
Why: why hub-and-spoke
- Single source of truth: all state lives in etcd, and only the apiserver reads and writes it. This ensures validation, admission, and auditing happen in one place.
- Decoupled components: the scheduler does not know the kubelet exists. It only writes
nodeName. The kubelet only cares about Pods whosenodeNameis its own. Any component can be restarted or replaced independently (for example, a custom scheduler). - Scalable: the watch mechanism means thousands of kubelets do not need to poll, and the apiserver's watch cache handles the fan-out.
- Security boundary: etcd holds sensitive data such as Secrets, which only the apiserver can access. Through the Node authorizer, a kubelet on a node can read only the objects related to itself.
How: static Pods and bootstrapping
kubeadm (and kind) run etcd, the apiserver, controller-manager, and scheduler as static Pods. The kubelet reads /etc/kubernetes/manifests/*.yaml directly on the control plane node and starts the containers. The apiserver does not need to exist first (this solves the chicken-and-egg problem). The kubelet then creates a read-only mirror pod for each one in the API, so you can see kube-apiserver-lab-control-plane in kube-system. Deleting it with kubectl does not help, because the kubelet recreates it right away.
When: managed vs self-managed
| kind / kubeadm (self-managed) | AKS (managed) | |
|---|---|---|
| Control plane | You can docker exec into it to look around and edit the static Pod manifests | Run by Azure in a managed subscription, not visible. Only the API endpoint is exposed. The SLA depends on the tier (Free/Standard/Premium). |
| etcd backup and upgrades | You are responsible | Azure handles it; you trigger version upgrades (or turn on the automatic upgrade channel) |
| Node | You are responsible | VMSS node pools; node images are published by Azure, and you decide when to upgrade |
| What you see in kube-system | All components | CoreDNS, kube-proxy (or replaced by Cilium), CNI/CSI drivers, metrics-server, konnectivity-agent, etc.; no apiserver/etcd Pods |
kubectl logs/exec also goes kubectl → apiserver → kubelet (port 10250). (3) “kube-proxy forwards every packet.” In iptables/nftables mode, it only writes rules. The kernel forwards the packets, and existing rules keep working even if kube-proxy stops. (4) “The Kubernetes runtime is Docker.” dockershim was removed in v1.24. Nodes run containerd instead (OCI images built by Docker still work).Figure 2-1: Cluster architecture (kind cluster lab)
Figure 2-2: Inside a node, from kubelet to container process
Interactive animation: who watches whom? (hub-and-spoke)
Click “Play” to step through each component's relationship with the apiserver, or click a component button below. After each step, the terminal below shows the API requests that component actually makes (watch requests include ?watch=true).
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl get nodes -o wide | Nodes, versions, internal IP, runtime | -L node-role.kubernetes.io/control-plane |
kubectl get pods -n kube-system -o wide | View system component Pods | Static Pod names include the node name as a suffix |
kubectl get --raw '/readyz?verbose' | Details of the apiserver readiness checks | /livez, /readyz; /healthz is no longer recommended |
kubectl describe node NODE | Conditions, capacity, allocated resources, taints, events | Troubleshoot NotReady and insufficient resources |
kubectl get leases -n kube-node-lease | Node heartbeat | RENEW time should be within a few seconds |
crictl ps / pods / images / logs | Talk to CRI directly on the node (similar to docker ps) | Included in kind nodes; troubleshoot at the kubelet layer |
journalctl -u kubelet | kubelet logs | -f, --since "10 min ago" |
kubectl get pods -n kube-system -o wide
NAME READY STATUS RESTARTS AGE IP NODE coredns-7c65d6cfc9-4tq7v 1/1 Running 0 10m 10.244.0.3 lab-control-plane coredns-7c65d6cfc9-tv2xl 1/1 Running 0 10m 10.244.0.2 lab-control-plane etcd-lab-control-plane 1/1 Running 0 10m 172.18.0.4 lab-control-plane kindnet-8xq2d 1/1 Running 0 10m 172.18.0.2 lab-worker kindnet-jk4f9 1/1 Running 0 10m 172.18.0.4 lab-control-plane kindnet-r7mzc 1/1 Running 0 10m 172.18.0.3 lab-worker2 kube-apiserver-lab-control-plane 1/1 Running 0 10m 172.18.0.4 lab-control-plane kube-controller-manager-lab-control-plane 1/1 Running 0 10m 172.18.0.4 lab-control-plane kube-proxy-5bdl2 1/1 Running 0 10m 172.18.0.3 lab-worker2 kube-proxy-9sjwm 1/1 Running 0 10m 172.18.0.4 lab-control-plane kube-proxy-tq8hn 1/1 Running 0 10m 172.18.0.2 lab-worker kube-scheduler-lab-control-plane 1/1 Running 0 10m 172.18.0.4 lab-control-plane
Observe: control plane components, kube-proxy, and kindnet use hostNetwork (their IP equals the node IP). CoreDNS uses a Pod network IP. kube-proxy and kindnet are DaemonSets (one per node).
kubectl get --raw '/readyz?verbose' | head -12; echo ... kubectl get --raw '/livez'; echo
[+]ping ok [+]log ok [+]etcd ok [+]etcd-readiness ok [+]informer-sync ok [+]poststarthook/start-apiserver-admission-initializer ok [+]poststarthook/generic-apiserver-start-informers ok ... readyz check passed ok
kubectl -n kube-system get cm kube-proxy -o jsonpath='{.data.config\.conf}' | grep -E '^mode'
mode: iptables
- How to verify: All checks show
[+]. Any[-]check explains why it failed (for example, etcd is unreachable). - Common mistake: On AKS, to run
crictl, first get onto the node withkubectl debug node/NODE -it --image=…. - Production use: load balancers and monitoring probe
/readyz. Before an upgrade, check that all nodes are Ready and look for kubelet version skew.
Lab 2: Take apart the kind control plane (about 6 min)
docker ps --format '{{.Names}}'
docker exec lab-control-plane ps -eo pid,comm | grep -E 'kube|etcd|containerd' | head
lab-control-plane
lab-worker
lab-worker2
200 containerd
490 kube-scheduler
502 kube-apiserver
517 etcd
530 kube-controller
690 kubeletdocker exec lab-control-plane crictl ps docker exec lab-control-plane crictl pods --namespace kube-system | head -5
CONTAINER IMAGE CREATED STATE NAME ATTEMPT POD ID POD 3c1f0d2a9e7b c69fa2e9cbf5 12 minutes ago Running coredns 0 8a2b1c... coredns-7c65d6cfc9-4tq7v 9b8e7f6d5c4a 2e96e5913fc0 13 minutes ago Running kube-proxy 0 5d4c3b... kube-proxy-9sjwm a1b2c3d4e5f6 0486b6c53a1b 13 minutes ago Running etcd 0 7e6f5a... etcd-lab-control-plane b2c3d4e5f6a7 aef2421e3a4b 13 minutes ago Running kube-apiserver 0 6f5e4d... kube-apiserver-lab-control-plane ...
docker exec lab-control-plane ls /etc/kubernetes/manifests docker exec lab-control-plane grep -E -- '--(etcd-servers|authorization-mode|enable-admission-plugins|service-cluster-ip-range)' /etc/kubernetes/manifests/kube-apiserver.yaml
etcd.yaml
kube-apiserver.yaml
kube-controller-manager.yaml
kube-scheduler.yaml
- --authorization-mode=Node,RBAC
- --enable-admission-plugins=NodeRestriction
- --etcd-servers=https://127.0.0.1:2379
- --service-cluster-ip-range=10.96.0.0/16
--etcd-servers shows that only the apiserver connects to etcd. Node,RBAC is the authorization setting covered in Module 5. The Service CIDR 10.96.0.0/16 is where the ClusterIPs in Module 8 come from.
kubectl -n kube-system delete pod kube-scheduler-lab-control-plane sleep 5; kubectl -n kube-system get pod kube-scheduler-lab-control-plane
pod "kube-scheduler-lab-control-plane" deleted NAME READY STATUS RESTARTS AGE kube-scheduler-lab-control-plane 1/1 Running 0 3s
Deleting only removes the mirror pod from the API. The container itself is managed by the kubelet from the manifest file, and the kubelet quickly recreates the mirror pod.
kubectl get --raw '/readyz?verbose' | grep etcd kubectl -n kube-system exec etcd-lab-control-plane -- etcdctl \ --endpoints=https://127.0.0.1:2379 \ --cacert=/etc/kubernetes/pki/etcd/ca.crt \ --cert=/etc/kubernetes/pki/etcd/server.crt \ --key=/etc/kubernetes/pki/etcd/server.key \ get /registry/namespaces/shop --keys-only
[+]etcd ok [+]etcd-readiness ok /registry/namespaces/shop
/registry/<resource>/<ns>/<name> (the values are protobuf-encoded). Never write to etcd directly, bypassing the apiserver.docker exec lab-worker journalctl -u kubelet --no-pager -n 5 kubectl get leases -n kube-node-lease
kubectl get pods -n kube-system does not show the apiserver, etcd, or scheduler. kubectl get --raw /readyz?verbose still works. No cleanup needed (this lab creates no resources).Case 1: etcd member count and availability
Problem: A self-managed cluster scaled etcd to 4 members for “higher availability.” Then 2 of them failed, and the whole cluster went read-only.
Approach: Raft needs a majority (quorum = ⌊n/2⌋+1). 3 members tolerate 1 failure, and 5 members tolerate 2. 4 members tolerate only 1, the same as 3, and add write amplification. In production, use 3 or 5 members spread across availability zones, use SSDs, and take regular etcdctl snapshot save backups.
Limits: On managed services such as AKS, the platform handles these. Your responsibility is API request volume. Heavy LIST traffic can overwhelm the apiserver and etcd.
Case 2: LIST storm from controllers or clients
Problem: A monitoring script runs kubectl get pods -A -o json every 5 seconds. The cluster has 20,000 Pods, and apiserver memory and latency spike.
Approach: Switch to an informer (one LIST, then incremental WATCH). When you must LIST, add resourceVersion=0 to read from the watch cache, use paginated limit, and narrow the scope with label or field selectors. API Priority and Fairness (APF) limits runaway clients. kubectl get flowschemas shows the priority levels.
Case 3: Migrating kube-proxy from ipvs to nftables
Problem: Years ago, the cluster chose ipvs mode for performance. The v1.37 release notes announce that ipvs is deprecated (expected to be disabled by default in v1.40 and removed in v1.43).
Approach: On a test cluster, set kube-proxy to mode: nftables (GA in v1.33; v1.37 switches to the netlink interface for better performance). Verify NodePort, externalTrafficPolicy, and rule sync time with many Services. The node kernel must be recent enough to support nftables. For managed clusters, follow your cloud provider's instructions (AKS may use Cilium in place of kube-proxy).
Common errors and fixes
NAME STATUS ROLES AGE VERSION
lab-worker2 NotReady <none> 20m v1.37.0
Cause: the kubelet stopped reporting heartbeats; the CNI is not ready (NetworkPluginNotReady); disk or memory pressure; or the kubelet refuses to start on a cgroup v1 host.
kubectl describe node lab-worker2 | sed -n '/Conditions/,/Addresses/p' docker exec lab-worker2 systemctl status kubelet --no-pager docker exec lab-worker2 journalctl -u kubelet --no-pager -n 50 | grep -iE 'error|fail'
If the logs show cgroup v1 errors, switch the host to cgroup v2 (since v1.35, the kubelet defaults to failCgroupV1: true).
The connection to the server 127.0.0.1:41234 was refused - did you specify the right host or port?
Cause: the kind node container stopped (for example, Docker did not restart the containers after a VM reboot), the apiserver crashed, or the kubeconfig points to an old cluster.
docker ps -a --filter name=lab- docker start lab-control-plane lab-worker lab-worker2 kubectl config current-context docker exec lab-control-plane crictl ps -a --name kube-apiserver docker exec lab-control-plane crictl logs $(docker exec lab-control-plane crictl ps -a -q --name kube-apiserver | head -1) 2>&1 | tail -20
coredns Pod stays Pending or in CrashLoopBackOff
Cause: Pending usually means the CNI is not ready yet (the NotReady node has a taint). CrashLoopBackOff is often caused by the host's /etc/resolv.conf pointing to 127.0.0.53, which creates a forwarding loop. The loop plugin detects it and exits.
kubectl -n kube-system logs -l k8s-app=kube-dns --tail=20 kubectl -n kube-system get cm coredns -o yaml | grep -A3 forward
Error from server (Forbidden): pods "kube-apiserver-lab-control-plane" is forbidden ... / Changes to the mirror pod have no effect
Cause: You cannot change a static Pod's mirror pod through the API. To change its settings, edit /etc/kubernetes/manifests/*.yaml on the node. The kubelet detects the file change and recreates the container.
docker exec -it lab-control-plane vi /etc/kubernetes/manifests/kube-apiserver.yaml # Do this only in a lab environment
1. Without using kubectl, list the names of the running containers on the lab-worker node.
docker exec lab-worker crictl ps -o table | awk 'NR>1{print $6}'
# Or simply: docker exec lab-worker crictl ps2. List all DaemonSet-managed workloads in kube-system, along with their ready counts.
kubectl -n kube-system get daemonsets
A colleague says: “kube-scheduler is down, so all existing Pods will stop. We have to fix it right now.” Is that correct? What is the real impact?
Not correct. The scheduler only chooses nodes for new, unscheduled Pods. Running Pods are maintained by each node's kubelet, so they are not affected. Service forwarding rules are maintained by kube-proxy, so they are not affected either. The real impact: new Pods, scaled-up Pods, and Pods recreated after eviction stay Pending (no Scheduled event appears). In kubeadm or kind, it is a static Pod. Check crictl ps -a --name kube-scheduler and its logs. On AKS, Azure manages the control plane. Similarly, if controller-manager goes down, existing Pods keep running, but they will not self-heal or roll out. If the apiserver goes down, existing traffic usually still flows, but all changes and self-healing stop.
Verified teaching videos
Official docs
- Kubernetes Components
- Cluster Architecture
- Create static Pods
- Virtual IPs and Service Proxies (kube-proxy modes)
- API server health endpoints
Video storyboard script
This course material cannot generate video or MP3 files directly, so it provides the storyboard and narration script.
Visual: The apiserver glows in the center, surrounded by the scheduler, controller-manager, kubelet, and kube-proxy. All the lines point to the center.
Narration: “Kubernetes is built like a hub. Every component talks only to the API server.”
Visual: Three etcd members vote, with the Raft majority marked. A lock shows that only the apiserver can access it.
Narration: “State is stored in etcd. It uses Raft to stay consistent, and only the API server can read or write it.”
Visual: The scheduler sees a Pod with no node, scores the nodes, and writes the nodeName. The kubelet sees it and calls containerd through CRI.
Narration: “The scheduler only decides where a Pod goes. The kubelet is responsible for actually starting it. The two never communicate directly.”
Visual: kind terminal: docker exec crictl ps, then ls /etc/kubernetes/manifests.
Narration: “In kind, the control plane is made of static Pods, and you can see them for yourself.”
Visual: AKS icon: the control plane is hidden behind a cloud, and only the API endpoint is visible.
Narration: “On AKS, Azure manages the control plane. You are responsible only for the nodes and workloads.”
Module 3 · kubectl and the API object model
- Read the three sections of a kubeconfig (clusters / users / contexts), and switch contexts and the default namespace with confidence.
- Understand the four sections of an API object (apiVersion / kind / metadata / spec, plus status), and the difference between GVK and GVR.
- Look up fields yourself with
api-resourcesandexplain, and extract information with-o yaml/json/jsonpath/custom-columns/wide/kyaml. - Generate manifests with
--dry-run=client|server -o yaml, preview changes withkubectl diff, and see the actual REST calls with-v=6/8andkubectl proxy.
What: kubeconfig
kubectl looks for configuration in this order: the --kubeconfig flag → $KUBECONFIG (you can merge multiple files with colons) → ~/.kube/config. The file has three sections:
| Section | Contents | Values in kind-lab |
|---|---|---|
clusters | API endpoint + CA certificate | server: https://127.0.0.1:41234 |
users | Identity credentials: client certificate, bearer token, or exec plugin (such as kubelogin for AKS) | The kubernetes-admin client certificate generated by kind (belongs to the kubeadm:cluster-admins group) |
contexts | A combination of cluster + user + default namespace | kind-lab |
What: API object model
apiVersion: apps/v1 # Group/Version: v1 of the apps group (the core group omits the group name and is written as v1) kind: Deployment # Kind: object type (singular, CamelCase) metadata: # Identity and metadata: name, namespace, labels, annotations, uid, resourceVersion, ownerReferences… name: api namespace: shop spec: # Desired state (you write it) replicas: 3 ... status: # Actual state (written by the controller through the status subresource); do not write it in manifests readyReplicas: 3
| Concept | Meaning | Example |
|---|---|---|
| GVK (Group-Version-Kind) | The object's “type,” written in YAML | apps/v1, Kind=Deployment |
| GVR (Group-Version-Resource) | The “resource” in the REST path, in lowercase plural | /apis/apps/v1/namespaces/shop/deployments |
| core group | Legacy; paths start with /api/v1 | /api/v1/namespaces/shop/pods |
| Subresources | Extra endpoints on objects | pods/log, pods/exec, pods/binding, deployments/scale, */status |
| Version stages | alpha (off by default) → beta → GA (v1) | v1alpha1, v1beta1, v1 |
Why: why you need to understand these
- RBAC rules are written as a resource (GVR) + verbs (get/list/watch/create/update/patch/delete). Without understanding GVRs, you can't write correct permissions (covered in hour 5).
- CRDs (such as the Gateway API
HTTPRoute) are discovered withapi-resources/explain, just like built-in resources. You don't need to memorize the docs. - When troubleshooting,
-v=8shows exactly what request kubectl sent and what status code the apiserver returned.
How: choosing an output format
| Format | Use |
|---|---|
-o wide | Table with extra columns (Pod IP, node) |
-o yaml / -o json | Full object; json works well with jq |
-o kyaml | KYAML: a strict subset of YAML (always-quoted strings, explicit {}/[]) that avoids ambiguities such as the “Norway problem” (NO → false). GA in v1.37 |
-o jsonpath='{…}' | Extract fields in scripts |
-o custom-columns=… | Custom columns |
-o name | Prints only kind/name, which is handy for pipes |
When: client or server dry-run
--dry-run=client: doesn't contact the server (or makes only minimal calls) and only generates the object. Use it to generate YAML templates.--dry-run=server: the request goes through authentication, authorization, mutating admission, validation, and validating admission, but nothing is written to etcd. Use it to check whether the cluster will accept a manifest (including policies).kubectl diffis essentially a server-side dry-run followed by a comparison with the existing object.
kubectl get -o yaml can be committed to Git as is.” It includes server fields such as status, uid, resourceVersion, and managedFields, so you need to clean it up. ② “Just use the latest apiVersion.” Removed versions (such as extensions/v1beta1) fail with no matches for kind. ③ “The Kind name and the resource name are the same.” The Kind is Deployment, the resource is deployments, and the short name is deploy.Figure 3-1: kubeconfig structure
Figure 3-2: from a kubectl command to a REST path (GVK → GVR)
Interactive 1: YAML field explainer (click any highlighted field)
It shows the field's meaning, who writes it (you, a controller, or the apiserver), and the matching kubectl explain path.
Interactive 2: line-by-line walkthrough of kubectl get pods -n shop -v=8
Click “Next line” to step through the -v=8 log. Newer kubectl versions use structured logging, so the format varies slightly by version. The panel on the right explains what each line means.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl config get-contexts | List contexts; * marks the current one | current-context, view --minify |
kubectl config use-context NAME | Switch cluster/identity | For production clusters, use a different terminal color or the kubectx tool |
kubectl config set-context --current --namespace=shop | Set the default namespace for the current context | Avoids typing -n on every command |
kubectl api-resources | List resource names, short names, group versions, whether they are namespaced, and Kinds | --namespaced=false, --api-group=apps, -o wide (shows verbs) |
kubectl api-versions | List the group/versions the server supports | Check whether a beta API is enabled |
kubectl explain | Look up fields in the server's OpenAPI document | --recursive, --api-version |
kubectl create … --dry-run=client -o yaml | Generate manifest templates | deployment, service, configmap, secret, job, cronjob… |
kubectl diff -f | Preview changes | KUBECTL_EXTERNAL_DIFF="diff -u --color" |
kubectl get … -v=6/8/9 | Show HTTP requests (6: URL and status code; 8: adds truncated request/response bodies; 9: full) | Investigate permissions and slow requests |
kubectl proxy | Local proxy that adds authentication automatically | --port=8001; listens on 127.0.0.1 only |
kubectl config get-contexts
kubectl config set-context --current --namespace=shop
kubectl config view --minify -o jsonpath='{..namespace}{"\n"}'
CURRENT NAME CLUSTER AUTHINFO NAMESPACE * kind-lab kind-lab kind-lab Context "kind-lab" modified. shop
kubectl api-resources --api-group=apps kubectl api-versions | grep -E '^(apps|batch|networking|metrics)'
NAME SHORTNAMES APIVERSION NAMESPACED KIND controllerrevisions apps/v1 true ControllerRevision daemonsets ds apps/v1 true DaemonSet deployments deploy apps/v1 true Deployment replicasets rs apps/v1 true ReplicaSet statefulsets sts apps/v1 true StatefulSet apps/v1 batch/v1 networking.k8s.io/v1
kubectl explain deployment.spec.strategy --recursive
GROUP: apps
KIND: Deployment
VERSION: v1
FIELD: strategy <DeploymentStrategy>
DESCRIPTION:
The deployment strategy to use to replace existing pods with new ones.
FIELDS:
rollingUpdate <RollingUpdateDeployment>
maxSurge <IntOrString>
maxUnavailable <IntOrString>
type <string>
enum: Recreate, RollingUpdate
kubectl get pods -o wide
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\t"}{.spec.nodeName}{"\n"}{end}'
kubectl get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[0].image,NODE:.spec.nodeName,PHASE:.status.phase'
kubectl get deploy api -o kyaml | head -20
{
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "api",
namespace: "shop",
...
},
spec: {
replicas: 3,
...
kubectl create deployment api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=3 --port=9898 \ --dry-run=client -o yaml > api-deploy.yaml kubectl apply -f api-deploy.yaml --dry-run=server sed -i 's/replicas: 3/replicas: 4/' api-deploy.yaml kubectl diff -f api-deploy.yaml; echo "exit=$?"
deployment.apps/api configured (server dry run) - replicas: 3 + replicas: 4 exit=1
kubectl proxy --port=8001 & curl -s localhost:8001/api/v1/namespaces/shop/pods | jq -r '.items[].metadata.name' curl -s localhost:8001/apis/apps/v1/namespaces/shop/deployments/api | jq '.status' curl -s "localhost:8001/api/v1/namespaces/shop/pods?watch=true&timeoutSeconds=10" | jq -r '.type + " " + .object.metadata.name' kill %1
- How to verify: the JSON returned by curl matches
kubectl get -o json. (kubectl requests the Table format by default.) - Common mistake: binding
kubectl proxyto 0.0.0.0 exposes admin access to the network. Never do this. - Production use: in CI,
kubectl apply --dry-run=servercatches admission policy rejections early, andkubectl diffserves as a change review.
Lab 3: Think Like the API Server (about 5 minutes)
kubectl config view --minify | grep -E 'server|name:|namespace' kubectl config set-context --current --namespace=shop
kubectl api-resources --namespaced=false | grep -iE 'storage|persistentvolume|csi'
persistentvolumes pv v1 false PersistentVolume csidrivers storage.k8s.io/v1 false CSIDriver csinodes storage.k8s.io/v1 false CSINode storageclasses sc storage.k8s.io/v1 false StorageClass volumeattachments storage.k8s.io/v1 false VolumeAttachment
restartPolicy take? What is the default?
kubectl explain pod.spec.restartPolicy
Answer: Always / OnFailure / Never; the default is Always (see DESCRIPTION in the output).
mkdir -p ~/k8slab/m3 && cd ~/k8slab/m3 kubectl create deployment api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=2 --port=9898 --dry-run=client -o yaml > api.yaml kubectl apply -f api.yaml kubectl get deploy api -o custom-columns='NAME:.metadata.name,GEN:.metadata.generation,OBSERVED:.status.observedGeneration,RV:.metadata.resourceVersion'
generation increases by 1 each time the spec changes. observedGeneration is the version the controller has processed. When the two are equal, the controller has seen the latest desired state. resourceVersion is the etcd revision number, used for optimistic concurrency and for resuming watches.
kubectl get deploy api -v=6 2>&1 | grep -E 'GET|Response' kubectl scale deploy api --replicas=3 -v=8 2>&1 | grep -E 'PATCH|Request Body|Response Status|"verb"' | head
I1115 10:02:11.482913 4211 round_trippers.go:632] "Response" verb="GET" url="https://127.0.0.1:41234/apis/apps/v1/namespaces/shop/deployments/api" status="200 OK" milliseconds=6 ... "Request" verb="PATCH" url="https://127.0.0.1:41234/apis/apps/v1/namespaces/shop/deployments/api/scale" ... ... "Response" verb="PATCH" ... status="200 OK" milliseconds=9
Note that scale goes through the deployments/scale subresource, so RBAC can grant it separately.
kubectl proxy. In a second terminal, run curl -N "localhost:8001/api/v1/namespaces/shop/pods?watch=true". In a third terminal, delete one api Pod and watch the JSON event stream for "type":"MODIFIED", "type":"DELETED", and "type":"ADDED".kubectl delete -f ~/k8slab/m3/api.yaml, then stop the proxy (Ctrl+C).Case 1: Running a command against the production cluster by mistake
Problem: An engineer thought they were in the test context and ran kubectl delete ns payments. The current context was actually the production AKS cluster.
Fix: ① Keep a separate kubeconfig file for each cluster and select it explicitly with KUBECONFIG. ② Show the current context and namespace in the shell prompt (for example, with kube-ps1). ③ Give production users read-only RBAC by default, and route writes through CI/GitOps. ④ On AKS, use Entra ID with kubelogin so tokens are short-lived and long-lived admin certificates are avoided (run az aks get-credentials without --admin).
Case 2: Upgrade failure caused by API deprecation
Problem: After a cluster upgrade, a Helm release failed with no matches for kind "PodDisruptionBudget" in version "policy/v1beta1".
Fix: Before upgrading, check the apiVersions in your manifests with kubectl api-versions and the official Deprecated API Migration Guide. Scan your repositories with the kubectl convert plugin or tools such as pluto. The apiserver metric apiserver_requested_deprecated_apis can reveal clients that still call old APIs.
Case 3: Extracting fields reliably in scripts
Problem: An ops script used kubectl get pods | awk '{print $3}' to read status. After a kubectl upgrade changed the columns, the script broke.
Fix: In scripts, use only -o jsonpath, -o json | jq, or -o custom-columns. To wait for a condition, use kubectl wait --for=condition=Available deploy/api --timeout=120s. Don't poll with sleep and parse table output.
Common errors and fixes
error: the server doesn't have a resource type "deploymnet"
Cause: A typo, or the resource is provided by a CRD that isn't installed yet (for example, httproutes).
kubectl api-resources | grep -i deploy kubectl get crd | grep -i gateway
error: resource mapping not found for name: "api" namespace: "" from "api.yaml": no matches for kind "Deployment" in version "extensions/v1beta1"
Cause: A removed API version is in use (the extensions/v1beta1 version of Deployment was removed in v1.16).
kubectl explain deployment | head -3 # Check the current version: apps/v1 kubectl api-versions | grep apps
Change it to apiVersion: apps/v1, and add the spec.selector that v1 requires.
Error from server (Forbidden): pods is forbidden: User "dev@contoso.com" cannot list resource "pods" in API group "" in the namespace "shop"
Cause: Authentication succeeded (the apiserver knows who you are), but RBAC authorization failed.
kubectl auth whoami kubectl auth can-i list pods -n shop kubectl auth can-i --list -n shop
A cluster admin needs to grant a Role/RoleBinding (covered in hour 5).
error: You must be logged in to the server (Unauthorized)
Cause: Authentication failed. The certificate or token has expired, or the kubeconfig points to a cluster that was rebuilt (the CA changed).
kubectl config view --minify --raw -o jsonpath='{.users[0].user.client-certificate-data}' | base64 -d | openssl x509 -noout -enddate
kind get kubeconfig --name lab > /tmp/lab.kubeconfig # kind: re-export
# AKS: az aks get-credentials -g rg-k8s-lab -n aks-lab --overwrite-existing1. Print the name and node of each Pod in the shop namespace, with the two columns separated by a tab.
kubectl -n shop get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}'2. Without creating any resources, verify that api.yaml passes all of the cluster's validation and admission checks.
kubectl apply -f api.yaml --dry-run=server
You need to write a manifest for a CRD, but you don't know its field structure, and you can't look up the docs online. What do you do?
After a CRD is installed, its OpenAPI v3 schema is published to the apiserver. First, find the resource name and group version with kubectl api-resources | grep keyword. Then view the full field tree with kubectl explain <resource>.spec --recursive. You can check the schema and available versions with kubectl get crd <name> -o yaml. After you write the manifest, validate it with --dry-run=server. Schema validation points out unknown or wrongly typed fields. kubectl enables server-side field validation by default with --validate=strict.
Verified video lessons
Official docs
- Organizing Cluster Access Using kubeconfig Files
- Objects In Kubernetes
- kubectl Quick Reference
- JSONPath Support
- Kubernetes API Concepts (watch, resourceVersion)
- Deprecated API Migration Guide
Video storyboard script
This courseware cannot generate video or MP3 files directly, so a storyboard and narration script are provided instead.
Visual: A kubeconfig file splits into three blocks: cluster, user, and context.
Narration: “Which cluster kubectl connects to, and as whom, is decided entirely by the context in your kubeconfig.”
Visual: A Deployment YAML splits into four colored blocks: apiVersion, kind, metadata, and spec, with a gray status block below.
Narration: “Every object has four parts: version, type, metadata, and desired state. Controllers write back the status.”
Visual: In the terminal, you type kubectl explain deployment.spec.strategy --recursive, and the field tree expands.
Narration: “Can't remember a field? Ask the API server. explain is documentation you can use offline.”
Visual: The -v=8 log is highlighted line by line: GET, the URL, 200 OK, and the timing in milliseconds.
Narration: “Add v=8, and you'll see that kubectl is just sending HTTPS requests.”
Module 4 · Pod: The Smallest Scheduling Unit
- Explain how Pods and containers relate: they share the network and IPC namespaces (and optionally the PID namespace), which are held by the pause container (sandbox).
- Use multi-container patterns: initContainers, native sidecars (
initContainers+restartPolicy: Always), and the adapter/ambassador patterns. - Distinguish a Pod's phase (Pending/Running/Succeeded/Failed/Unknown) from container state (Waiting/Running/Terminated), and know the common reasons.
- Use run / get / describe / logs (-c, --previous, -f) / exec / port-forward / delete / debug to diagnose Pods.
What: what a Pod is
A Pod is the smallest unit Kubernetes uses for scheduling, scaling, and network addressing. All containers in a Pod are scheduled to the same node. They share the same IP address and port space (the network namespace) and the IPC namespace, can share volumes, and can optionally share the PID namespace (shareProcessNamespace: true). Each container still has its own mount namespace and cgroup, and resource limits are set per container.
On the node, the kubelet first calls RunPodSandbox through CRI. containerd starts a tiny pause container (registry.k8s.io/pause). The pause container creates and holds the network and IPC namespaces, and CNI assigns the IP. Application containers then start by joining the pause container's namespaces. The IP stays the same when an application container restarts, because the pause container holds the namespaces.
Why: why not just one container
- Some processes need to be tightly coupled: a logging sidecar reads the same emptyDir, a service mesh proxy intercepts localhost traffic, and a config reloader sends signals to the main process.
- Each container does one job (single responsibility), and a Pod provides the combination of living and dying together while sharing local resources.
How: multi-container patterns
| Pattern | How to write it | Behavior | Typical uses |
|---|---|---|---|
| initContainers | spec.initContainers[] | Runs one at a time, in order, until each exits successfully. The main containers start only after all of them finish. Failures are retried according to restartPolicy. | Waiting for dependencies, database migrations, downloading config, setting permissions |
| Native sidecar (v1.33 GA) | Set restartPolicy: Always in initContainers[] | Starts before the main containers and keeps running. It can have startup and readiness probes. It is terminated only after the main containers exit. It does not block Job completion. | Log/metrics agents, service mesh proxies, certificate rotation |
| Traditional sidecar | A second container in containers[] | Starts in parallel with the main container, with no startup order guarantee. It blocks Job completion. | Legacy approach; prefer native sidecars in new projects |
| Adapter / Ambassador | A specialized sidecar | Transform output format / proxy external connections | Prometheus exporter, local database proxy |
| Ephemeral container | kubectl debug -it POD --image=busybox:1.37 --target=app | Injected into a running Pod at runtime. It cannot be restarted and has no ports or probes. | Debugging distroless images |
Pod phase and container state
| Pod phase | Meaning |
|---|---|
Pending | Accepted by the API, but at least one container is not running yet: waiting to be scheduled, pulling images, or running init containers |
Running | Bound to a node, all containers created, and at least one container running (or starting or restarting) |
Succeeded | All containers terminated successfully (exit code 0) and will not restart. Typical for Job Pods. |
Failed | All containers have terminated, and at least one ended in failure and will not restart (restartPolicy is Never or OnFailure, and no retries are left) |
Unknown | The Pod's state cannot be obtained, usually because communication with the node was lost |
| Container state | Common reasons | Meaning |
|---|---|---|
Waiting | ContainerCreating / PodInitializing | Creating the sandbox, mounting volumes, waiting for init to finish |
Waiting | ErrImagePull → ImagePullBackOff | Image pull failed (wrong image name or tag, no credentials for a private registry, or network issues). Retries follow a backoff. |
Waiting | CrashLoopBackOff | The container keeps exiting, and the kubelet is waiting in backoff (10s, 20s, 40s, … up to 5 minutes; reset after the container runs successfully for 10 minutes) |
Waiting | CreateContainerConfigError | Configuration error, such as a referenced ConfigMap or Secret, or one of its keys, does not exist |
Running | — | startedAt shows the start time |
Terminated | Completed (0) / Error (non-zero) / OOMKilled (137) | Includes exitCode, signal, and finishedAt. Information about the previous termination is in lastState. |
restartPolicy (Pod level): Always (the default; Deployments allow only Always), OnFailure, or Never (Jobs use the last two). Restarts happen on the same node, within the same Pod, and the RESTARTS count goes up. A controller rebuilds the Pod elsewhere only after the Pod itself is deleted.
When: when to create a Pod directly
In production, you almost never create a bare Pod (naked Pod) directly. It has no controller, so it is not recreated after a node failure or eviction. Use a Deployment (stateless), StatefulSet (stateful), DaemonSet (one per node), or Job/CronJob (batch). Bare Pods are only for temporary debugging (kubectl run tmp --rm -it).
logs --previous and lastState.terminated.Figure 4-1: Pod internals (podinfo + native sidecar + init)
Figure 4-2: Pod lifecycle and container states
Interactive state machine: trigger events and watch the Pod phase and container states
Choose a restartPolicy, then click an event button. The left side shows the STATUS column from kubectl get pod, which is a combined view of the phase and the container reason. The right side shows the actual values in the status field.
Core commands
| Command | Purpose | Key flags |
|---|---|---|
kubectl run NAME --image=IMG | Create a single Pod (for debugging or generating YAML) | --port --labels --env --restart=Never --rm -it -- command args |
kubectl get pod -o wide | IP, node, READY, RESTARTS | -w, --show-labels |
kubectl describe pod | Container states, lastState, conditions, volumes, Events | First step in troubleshooting |
kubectl logs | Container stdout/stderr | -c container --previous -f --tail --since=10m --all-containers -l app=x |
kubectl exec -it POD -- sh | Run a command in a container | -c; use debug when the image has no shell |
kubectl port-forward pod/P 8080:9898 | Forward a local port to a Pod through a tunnel via the apiserver | --address 127.0.0.1 |
kubectl debug | Ephemeral containers / copy a Pod / node debugging | -it --image --target, --copy-to, node/NODE |
kubectl delete pod | Delete (graceful termination by default, 30 seconds) | --grace-period=0 --force (use with caution), --wait=false |
kubectl run podinfo --image=ghcr.io/stefanprodan/podinfo:6.17.0 --port=9898 -l app=podinfo
kubectl get pod podinfo -o wide
kubectl get pod podinfo -o jsonpath='{.status.phase} {.status.containerStatuses[0].state}{"\n"}'
pod/podinfo created
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
podinfo 1/1 Running 0 8s 10.244.1.4 lab-worker <none> <none>
Running {"running":{"startedAt":"2026-11-15T10:12:03Z"}}
kubectl logs podinfo --tail=5 kubectl exec podinfo -- wget -qO- localhost:9898/version kubectl port-forward pod/podinfo 8080:9898 & curl -s localhost:8080/healthz; kill %1
{"level":"info","ts":"...","caller":"podinfo/main.go:...","msg":"Starting podinfo","version":"6.17.0",...}
{
"commit": "...",
"version": "6.17.0"
}
{
"status": "OK"
}
kubectl debug -it podinfo --image=busybox:1.37 --target=podinfo -- sh # Inside the debug container: ps aux # --target shares the PID namespace of the podinfo container, so you can see the podinfo process wget -qO- localhost:9898/env | head
- How to verify:
kubectl get pod podinfo -o jsonpath='{.spec.ephemeralContainers[*].name}'showsdebugger-xxxxx. - Common mistake: checking only
kubectl logs(the current instance) and forgetting--previous. During CrashLoopBackOff, the real error is in the logs from the previous run. - Production use: distroless images have no shell, so inject a tools container with
kubectl debug. For node-level problems, usekubectl debug node/NODE -it --image=…. The node's root filesystem is mounted at/host.
Lab 4: Multi-Container Pod + Create and Diagnose Two Classic Failures (about 8 minutes)
lab, with the default namespace already set to shop.mkdir -p ~/k8slab/m4 && cd ~/k8slab/m4
cat > pod-multi.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: api-demo
namespace: shop
labels:
app.kubernetes.io/name: api-demo
spec:
initContainers:
- name: wait-dns # ① Regular init: wait until cluster DNS is available, then exit
image: busybox:1.37
command: ["sh", "-c", "until nslookup kubernetes.default.svc.cluster.local; do echo waiting dns; sleep 2; done"]
- name: log-tail # ② Native sidecar (v1.33 GA): starts before the app and keeps running
image: busybox:1.37
restartPolicy: Always
command: ["sh", "-c", "while [ ! -f /logs/app.log ]; do sleep 1; done; tail -f /logs/app.log"]
volumeMounts:
- name: logs
mountPath: /logs
containers:
- name: app # ③ Main container
image: ghcr.io/stefanprodan/podinfo:6.17.0
command: ["sh", "-c", "./podinfo --port=9898 --level=info 2>&1 | tee -a /logs/app.log"]
ports:
- containerPort: 9898
name: http
volumeMounts:
- name: logs
mountPath: /logs
volumes:
- name: logs
emptyDir: {}
EOF
kubectl apply -f pod-multi.yaml
kubectl get pod api-demo -w
NAME READY STATUS RESTARTS AGE api-demo 0/2 Init:0/2 0 1s api-demo 0/2 Init:1/2 0 4s api-demo 0/2 PodInitializing 0 5s api-demo 2/2 Running 0 6s
READY shows 2/2: the native sidecar counts toward the ready containers. The regular init container wait-dns has already exited, so it is not counted. The podinfo image is based on Alpine and includes sh. If you switch to a distroless image, this tee approach won't work. Also, sh -c as PID 1 does not forward SIGTERM, so deleting the Pod waits the full 30-second grace period (the issue covered in Module 3 of the Docker course). This is only a demo of a shared volume. In production, have the application write directly to stdout.
kubectl exec api-demo -c log-tail -- wget -qO- localhost:9898/healthz # sidecar reaches app via localhost
kubectl logs api-demo -c log-tail --tail=3 # sidecar reads the logs app wrote to the emptyDir
kubectl get pod api-demo -o jsonpath='{range .status.initContainerStatuses[*]}{.name}{"="}{.state}{"\n"}{end}'
{
"status": "OK"
}
wait-dns={"terminated":{"exitCode":0,"reason":"Completed",...}}
log-tail={"running":{"startedAt":"..."}}kubectl run badimg --image=ghcr.io/stefanprodan/podinfo:9.9.9 sleep 15; kubectl get pod badimg kubectl describe pod badimg | sed -n '/Events/,$p'
NAME READY STATUS RESTARTS AGE badimg 0/1 ImagePullBackOff 0 16s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 16s default-scheduler Successfully assigned shop/badimg to lab-worker2 Normal Pulling 15s kubelet Pulling image "ghcr.io/stefanprodan/podinfo:9.9.9" Warning Failed 14s kubelet Failed to pull image "ghcr.io/stefanprodan/podinfo:9.9.9": ... not found Warning Failed 14s kubelet Error: ErrImagePull Normal BackOff 2s kubelet Back-off pulling image "ghcr.io/stefanprodan/podinfo:9.9.9" Warning Failed 2s kubelet Error: ImagePullBackOff
Diagnosis: If Scheduled succeeded, the problem is not scheduling. In the Failed message, not found means the tag does not exist, unauthorized/403 means a credential problem (imagePullSecrets or the ACR integration on AKS), and i/o timeout means a network problem. Fix: kubectl set image pod/badimg badimg=ghcr.io/stefanprodan/podinfo:6.17.0. (The image field of a Pod is one of the few fields that can be changed in place.)
kubectl run crash --image=busybox:1.37 -- sh -c 'echo "connecting to db..."; sleep 3; echo "FATAL: DB_HOST not set" >&2; exit 1'
sleep 40; kubectl get pod crash
kubectl logs crash --previous
kubectl get pod crash -o jsonpath='{.status.containerStatuses[0].lastState.terminated}{"\n"}'
NAME READY STATUS RESTARTS AGE
crash 0/1 CrashLoopBackOff 2 (15s ago) 40s
connecting to db...
FATAL: DB_HOST not set
{"containerID":"containerd://…","exitCode":1,"finishedAt":"…","reason":"Error","startedAt":"…"}
Diagnosis: exitCode 1 = an application error (check the logs). 137 with reason OOMKilled = memory limit exceeded. 137 without OOM = killed with SIGKILL (for example, after a liveness probe failure and timeout). 127 = command not found. 0 but restarting repeatedly = the main process exits after finishing its work (Deployments allow only restartPolicy Always).
kubectl run oom --image=busybox:1.37 --overrides='{"spec":{"containers":[{"name":"oom","image":"busybox:1.37","command":["sh","-c","head -c 300m /dev/zero | tail"],"resources":{"limits":{"memory":"64Mi"}}}]}}'
sleep 10; kubectl get pod oom -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}{" "}{.status.containerStatuses[0].lastState.terminated.exitCode}{"\n"}'
OOMKilled 137
kubectl delete pod api-demo badimg crash oom podinfo --ignore-not-found
Case 1: A service mesh proxy keeps a Job from ever finishing
Problem: The main container of a data migration Job finished, but the Pod stayed Running, because the injected proxy sidecar (the traditional style, in containers[]) never exits.
Fix: Switch to a native sidecar (initContainers + restartPolicy: Always, v1.33 GA). After the main container exits, the kubelet terminates the sidecar, so the Job completes normally. The sidecar also starts before the main container, which resolves the race where the proxy isn't ready when the app starts.
initContainers:
- name: proxy
image: envoyproxy/envoy:<pinned version tag or digest> # placeholder: replace with the proxy image provided by your mesh
restartPolicy: Always
startupProbe:
httpGet: { path: /ready, port: 15021 }
Limitation: the mesh or injector must support native sidecars. Newer versions of Istio and Linkerd support them. Check their docs for details.
Case 2: Troubleshooting a distroless image
Problem: The production image is based on distroless and has no shell, so kubectl exec -- sh fails with exec: "sh": executable file not found in $PATH.
Fix: Inject an ephemeral container with kubectl debug -it api-xxx --image=busybox:1.37 --target=app. It shares the target container's process namespace, so you can browse the application filesystem under /proc/1/root. For more tools, use nicolaka/netshoot. Note: an ephemeral container cannot be removed until the Pod is deleted, and you need RBAC permission for pods/ephemeralcontainers.
Case 3: The pitfall of running database migrations in an init container
Problem: A Deployment with 3 replicas runs database migrations in the init container of every Pod. During a rolling update, multiple migrations run concurrently and conflict on locks.
Fix: Move the migration into a separate Job (or a Helm hook or Argo CD PreSync) that runs once before the rollout. The init container should only do idempotent, read-only wait checks.
Common errors and fixes
STATUS: ImagePullBackOff · Failed to pull image "...": ... 401 Unauthorized / 403 Forbidden
Cause: The private registry has no credentials, or the credentials lack permission.
kubectl describe pod POD | grep -A3 Failed
kubectl create secret docker-registry regcred --docker-server=myacr.azurecr.io --docker-username=… --docker-password=…
kubectl patch serviceaccount default -p '{"imagePullSecrets":[{"name":"regcred"}]}'
# AKS + ACR: az aks update -g rg-k8s-lab -n aks-lab --attach-acr myacr (the kubelet managed identity gets AcrPull)STATUS: CrashLoopBackOff · Back-off restarting failed container app in pod api-xxx
Cause: The main process keeps exiting. CrashLoopBackOff itself is not the cause.
kubectl logs POD -c app --previous --tail=50
kubectl get pod POD -o jsonpath='{.status.containerStatuses[?(@.name=="app")].lastState.terminated}'
kubectl describe pod POD | grep -iE 'oom|exit code|liveness'
kubectl debug POD -it --copy-to=POD-debug --container=app -- sh # Copy the Pod, override the start command with sh, then run the process manuallySTATUS: CreateContainerConfigError · Error: configmap "api-config" not found
Cause: env, envFrom, or a volume references a ConfigMap, Secret, or key name that does not exist.
kubectl describe pod POD | grep -i error kubectl get cm,secret kubectl create configmap api-config --from-literal=LOG_LEVEL=info
You can also set optional: true on the reference (covered in hour 2).
STATUS: Init:CrashLoopBackOff / Init:0/2 stuck
Cause: An init container failed, or it is waiting for a condition that will never be met (a misspelled DNS name, or a dependency service that isn't deployed).
kubectl logs POD -c wait-dns
kubectl get pod POD -o jsonpath='{range .status.initContainerStatuses[*]}{.name}{" "}{.ready}{" "}{.restartCount}{"\n"}{end}'Pod stays in Terminating and won't delete
Cause: The node is unreachable (the kubelet cannot confirm the containers have stopped), a finalizer exists, or the application ignores SIGTERM and waits out the grace period.
kubectl get pod POD -o jsonpath='{.metadata.finalizers} {.spec.nodeName} {.metadata.deletionTimestamp}{"\n"}'
kubectl get node NODE
kubectl delete pod POD --grace-period=0 --force # Last resort: removes only the API object; containers on the node may still be running1. The container named app in Pod api-7f9 keeps crashing. View the last 30 lines of its log from before the previous crash.
kubectl logs api-7f9 -c app --previous --tail=30
2. Start a temporary busybox:1.37 Pod, open an interactive shell, and have the Pod delete itself when you exit.
kubectl run tmp --rm -it --image=busybox:1.37 --restart=Never -- sh
A Pod shows Running, RESTARTS is 47, and READY is 1/1. Users report intermittent 502 errors from the API. How do you analyze this?
Running with a high RESTARTS count means the container keeps restarting in place. It is unavailable during each restart (readiness briefly drops to 0). Steps: ① Use kubectl get pod -o jsonpath to check the reason and exitCode under lastState.terminated. OOMKilled: adjust the limits or look for a memory leak. Error with application logs: use logs --previous. 137 without OOM: the liveness probe may have failed and killed the container, so check the Liveness probe failed event in the describe output. ② Combine this with kubectl get events --field-selector involvedObject.name=POD. ③ With multiple replicas, check whether only the Pods on certain nodes are affected (node resource pressure). ④ After the fix, confirm RESTARTS stops increasing. Correct probe and resource configuration is the focus of hour 2.
Verified video lessons
No verified official video specifically covering native sidecars in v1.33 was found. Refer to the official blog and docs.
Official docs
Video storyboard script
This courseware cannot generate video or MP3 files directly, so a storyboard and narration script are provided instead.
Visual: A transparent pod shell holds a small pause block and two containers, labeled with one shared IP.
Narration: “A Pod is a group of containers that share a network. They have the same IP and reach each other over localhost.”
Visual: The init containers light up and go dark one after another. The sidecar lights up and stays on. Finally, the main container lights up.
Narration: “Init containers run in order and exit when they finish. A native sidecar starts first and stays running alongside the main container.”
Visual: State machine: Pending moves to Running. When a container crashes, it bounces back, with timers at 10 seconds, 20 seconds, and 40 seconds.
Narration: “When a container crashes, it restarts in place, and the wait between restarts doubles each time. That is CrashLoopBackOff.”
Visual: Terminal: the Events from kubectl describe, and kubectl logs --previous with FATAL highlighted.
Narration: “Start with the events, then check the previous logs. The exit code tells you whether it is an application error or an out-of-memory failure.”
Module 5 · The Full Journey of kubectl apply
- Distinguish client-side apply (the
last-applied-configurationannotation plus a three-way merge) from server-side apply (field ownership inmanagedFieldsplus conflict detection). - Describe the kube-apiserver request chain in order: authentication → authorization → mutating admission → schema validation → validating admission → write to etcd (resourceVersion).
- Describe the asynchronous chain after the write to etcd: Deployment controller → ReplicaSet controller → scheduler → kubelet → CRI → CNI → status → EndpointSlice.
- Use events,
-v=8, and--show-managed-fieldsto verify each step in a real cluster.
What: the two kinds of apply
Client-Side Apply (CSA, the default for kubectl apply) | Server-Side Apply (SSA, kubectl apply --server-side) | |
|---|---|---|
| Where the merge happens | On the kubectl side: compares ① the configuration from the last apply (annotation), ② the current file, and ③ the live state in the cluster, then calculates a strategic merge patch | apiserver: the request body is the complete intent (Content-Type: application/apply-patch+yaml) |
| State tracking | metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"] (the entire JSON) | metadata.managedFields: which manager (kubectl, helm, kube-controller-manager, ci…) owns each field |
| Multiple collaborators | Overwrite each other silently | If a field owned by another manager is changed, it returns 409 Conflict. You can use --force-conflicts to take ownership. |
| First-time creation | GET → 404 → POST …/deployments | Send a direct PATCH …/deployments/api (creates the object if it doesn't exist) |
| Best for | Personal or simple use cases, and compatibility with existing workflows | GitOps controllers (Argo CD and Flux support SSA), objects co-managed by several tools, and large objects (to avoid annotations exceeding 256 KB) |
Why: why you need to know the whole chain
Almost every case of “apply succeeded but the app didn't start” can be traced to one step in the chain. 403 is authorization. admission webhook ... denied is admission. Pending with no events points to the scheduler. FailedScheduling is in the filtering phase. ErrImagePull is kubelet/CRI. FailedCreatePodSandBox is CNI. When a Service is unreachable but the Pods look healthy, the cause is often the EndpointSlice or labels.
How: the apiserver's internal request chain
| # | Stage | What it does | Typical error on failure |
|---|---|---|---|
| 1 | Authentication | x509 client certificates (CN=user, O=group), Bearer tokens (ServiceAccount JWT), and OIDC (Entra ID). Produces user and groups. | 401 Unauthorized |
| 2 | Authorization | --authorization-mode=Node,RBAC: whether user is allowed to patch/create apps/deployments in shop | 403 Forbidden ... cannot create resource "deployments" |
| 3 | Mutating admission | Built-in plugins (such as ServiceAccount, DefaultTolerationSeconds, and LimitRanger), MutatingAdmissionWebhook (service mesh sidecar injection), and MutatingAdmissionPolicy (CEL, a newer feature; check the official docs for its current stage) | admission webhook "..." denied the request / webhook timeout |
| 4 | Schema validation | Field types, required fields, immutable fields (such as spec.selector), and unknown fields (fieldValidation=Strict) | 422 Unprocessable Entity ... field is immutable / unknown field |
| 5 | Validating admission | ValidatingAdmissionPolicy (CEL, v1.30 GA), ValidatingAdmissionWebhook (Kyverno/Gatekeeper), PodSecurity (for Pods), and ResourceQuota | ... is forbidden: ValidatingAdmissionPolicy '...' denied request / exceeded quota |
| 6 | Persist to etcd | Serialized (protobuf) and written to /registry/deployments/shop/api, and a new resourceVersion is assigned. The watch cache is notified, and then all watchers. | etcdserver: request timed out (rare) |
When: what happens after the write to etcd (all asynchronous)
When the apiserver returns 201 Created or 200 OK, there are no Pods in the cluster yet. Then: the Deployment controller receives an ADDED event and creates a ReplicaSet. The ReplicaSet controller creates 3 Pod objects, and each Pod creation request goes through authentication, authorization, and admission again. The scheduler picks a node for each Pod and binds it. The kubelet on that node discovers the Pod through its watch. CRI RunPodSandbox runs (the pause container and CNI ADD assign the IP). Then PullImage → CreateContainer → StartContainer. The kubelet PATCHes the Pod status. Once the Pod is ready, the EndpointSlice controller adds its IP to the Service's EndpointSlice, and kube-proxy on each node updates its rules.
pods/binding. ③ “Admission webhooks can only reject.” Mutating webhooks modify objects (for example, injecting a sidecar or adding default labels). So the object in etcd can differ from your YAML, and kubectl diff shows those differences. ④ “CSA and SSA can be mixed freely.” You can migrate between them, but mixing them can cause unexpected field ownership conflicts. Teams should standardize on one.Figure 5-1: Request chain (synchronous part)
Figure 5-2: Asynchronous convergence chain (driven by watches)
Core animation: kubectl apply -f api-deploy.yaml (shop/api, 3 replicas)
14 steps. Each step highlights the current component, and the terminal shows real API requests, watch events, or Kubernetes Events. You can switch between CSA and SSA to see how the step 1 request differs.
kubectl get events --sort-by=.lastTimestamp with animation steps 8–13: ScalingReplicaSet → SuccessfulCreate → Scheduled → Pulled → Created → Started. The order should match exactly.Core commands
| Command | Purpose | Key flags |
|---|---|---|
kubectl apply -f FILE | client-side apply | --dry-run=server, -R (recursive directories) |
kubectl apply --server-side -f FILE | server-side apply | --field-manager=NAME, --force-conflicts |
kubectl get events --sort-by=.lastTimestamp -w | Watch events by time | --field-selector involvedObject.name=X, --types=Warning; the kubectl events subcommand is also available |
kubectl get … -o yaml --show-managed-fields | Show managedFields (hidden by default) | View field owners |
kubectl apply -v=8 | Show the request method, URL, Content-Type, and response | 2>&1 | grep -E 'Request|Response' |
kubectl rollout status | Wait for asynchronous convergence to finish | --timeout=120s |
kubectl auth can-i | Verify the authorization stage | --as=USER, --as=system:serviceaccount:ns:sa |
kubectl apply --server-side -f api-deploy.yaml -v=8 2>&1 | grep -E '"verb"|Content-Type|Response' | head
... "Request" verb="PATCH" url="https://127.0.0.1:41234/apis/apps/v1/namespaces/shop/deployments/api?fieldManager=kubectl&fieldValidation=Strict&force=false" headers=< Content-Type: application/apply-patch+yaml > ... "Response" verb="PATCH" url="..." status="201 Created" milliseconds=14 deployment.apps/api serverside-applied
kubectl -n shop get deploy api -o yaml --show-managed-fields | grep -A6 managedFields
managedFields:
- apiVersion: apps/v1
fieldsType: FieldsV1
fieldsV1:
f:spec:
f:replicas: {}
manager: kubectl
operation: Apply
...
- manager: kube-controller-manager
operation: Update
subresource: status
kubectl -n shop get events --sort-by=.lastTimestamp -o custom-columns='TIME:.lastTimestamp,REASON:.reason,OBJECT:.involvedObject.name,MESSAGE:.message' | tail -15
- How to verify: SSA output shows
serverside-applied. Objects created by CSA have thelast-applied-configurationannotation (kubectl get deploy api -o jsonpath='{.metadata.annotations}'). - Common mistake:
kubectl get -o yaml | grep managedFieldsreturns nothing. kubectl hides managedFields by default, so add--show-managed-fields. - Production use: in CI, use
--server-side --field-manager=ci-pipeline. Conflicts cause failure, which prevents silently overwriting fields owned by others or by controllers.
Lab 5: Trace One apply (about 7 minutes)
mkdir -p ~/k8slab/m5 && cd ~/k8slab/m5
cat > api-deploy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: shop
labels:
app.kubernetes.io/name: api
app.kubernetes.io/part-of: shop
spec:
replicas: 3
selector:
matchLabels:
app.kubernetes.io/name: api
template:
metadata:
labels:
app.kubernetes.io/name: api
app.kubernetes.io/part-of: shop
spec:
containers:
- name: api
image: ghcr.io/stefanprodan/podinfo:6.17.0
ports:
- containerPort: 9898
name: http
EOFkubectl -n shop get events --sort-by=.lastTimestamp -w
kubectl auth can-i create deployments -n shop kubectl apply --server-side -f api-deploy.yaml --dry-run=server kubectl apply --server-side -f api-deploy.yaml kubectl -n shop rollout status deploy/api
0s Normal ScalingReplicaSet deployment/api Scaled up replica set api-7c6b9f8d5d from 0 to 3 0s Normal SuccessfulCreate replicaset/api-7c6b9f8d5d Created pod: api-7c6b9f8d5d-x2k4p 0s Normal Scheduled pod/api-7c6b9f8d5d-x2k4p Successfully assigned shop/api-7c6b9f8d5d-x2k4p to lab-worker2 0s Normal Pulled pod/api-7c6b9f8d5d-x2k4p Container image "ghcr.io/stefanprodan/podinfo:6.17.0" already present on machine 0s Normal Created pod/api-7c6b9f8d5d-x2k4p Created container: api 0s Normal Started pod/api-7c6b9f8d5d-x2k4p Started container api
kubectl -n shop get deploy,rs,pods -l app.kubernetes.io/name=api -o wide
kubectl -n shop get rs -l app.kubernetes.io/name=api -o jsonpath='{.items[0].metadata.ownerReferences[0].kind}/{.items[0].metadata.ownerReferences[0].name}{"\n"}'
kubectl -n shop get deploy api -o jsonpath='rv={.metadata.resourceVersion} gen={.metadata.generation} observed={.status.observedGeneration}{"\n"}'kubectl -n shop get deploy api -o yaml --show-managed-fields | grep -B2 -A8 'manager: kubectl' # Simulate another tool (field manager = "hotfix") trying to change replicas to 5 sed 's/replicas: 3/replicas: 5/' api-deploy.yaml | kubectl apply --server-side --field-manager=hotfix -f -
error: Apply failed with 1 conflict: conflict with "kubectl": .spec.replicas Please review the fields above--they currently have other managers. Here are the ways you can resolve this warning: ...
The conflict protects fields managed by kubectl. When you really need to take over, add --force-conflicts. After that, the field belongs to hotfix. After the lab, set the replicas back: kubectl apply --server-side --force-conflicts -f api-deploy.yaml.
kubectl -n shop create configmap csa-demo --from-literal=a=1 --dry-run=client -o yaml | kubectl apply -f -
kubectl -n shop get cm csa-demo -o jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}{"\n"}'
kubectl -n shop delete cm csa-demoPOD=$(kubectl -n shop get pod -l app.kubernetes.io/name=api -o name | head -1)
kubectl -n shop get $POD -o jsonpath='{.spec.tolerations}{"\n"}{.spec.volumes[0].name}{"\n"}{.spec.serviceAccountName}{"\n"}'
[{"effect":"NoExecute","key":"node.kubernetes.io/not-ready","operator":"Exists","tolerationSeconds":300},{"effect":"NoExecute","key":"node.kubernetes.io/unreachable","operator":"Exists","tolerationSeconds":300}]
kube-api-access-7q2lx
default
None of these are in your YAML. The DefaultTolerationSeconds admission plugin injects the tolerations, and the ServiceAccount admission plugin injects the kube-api-access-* projected volume.
Case 1: A failed admission webhook blocks deployments cluster-wide
Problem: All Pods of the policy engine's webhook crashed. Its ValidatingWebhookConfiguration set failurePolicy: Fail and matched all namespaces. As a result, no Pod could be created, including the webhook's own Pods (a chicken-and-egg problem).
Fix: ① Exclude kube-system and the webhook's own namespace from the webhook (namespaceSelector). ② Set a reasonable timeoutSeconds. ③ Where a rule can be expressed in CEL, prefer a ValidatingAdmissionPolicy (v1.30 GA). It runs inside the apiserver process and has no network dependency.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: no-latest-tag
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments"]
validations:
- expression: "object.spec.template.spec.containers.all(c, !c.image.endsWith(':latest') && c.image.contains(':'))"
message: "Images must use a pinned tag or digest. :latest is not allowed"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: no-latest-tag-shop
spec:
policyName: no-latest-tag
validationActions: ["Deny"]
matchResources:
namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: shop
Limitation: CEL cannot call external systems. If you need external data, such as image signature checks, you still need a webhook. See hour 5 for writing policies.
Case 2: GitOps and HPA fight over replicas
Problem: Git sets replicas: 3. HPA scales to 10, and each GitOps sync changes it back to 3, causing flapping.
Fix: When you use HPA, remove the spec.replicas field from the manifest so that HPA is the only manager of that field. SSA's managedFields makes it clear who owns replicas.
Case 3: apply succeeds, but Pods appear 2 minutes later
Problem: During a release on a large cluster, Pods appeared long after the Deployment was created.
Fix: Measure each stage of the chain. Check the ScalingReplicaSet time in the events (controller-manager queue delay), then SuccessfulCreate (the RS controller, which may be rejected by a ResourceQuota, with a FailedCreate event), then Scheduled (scheduling queue and filtering time, with the scheduler_pending_pods metric), then Pulled (image size and registry bandwidth). On managed clusters, control plane metrics are available through Azure Monitor managed Prometheus on AKS.
Common errors and fixes
The Deployment "api" is invalid: spec.selector: Invalid value: ...: field is immutable
Cause: spec.selector cannot be changed after a Deployment is created. Schema validation rejects the change.
kubectl -n shop get deploy api -o jsonpath='{.spec.selector}{"\n"}'
Fix: Keep the selector unchanged and change only the extra labels in the template. If you really must change the selector, create a new Deployment with a different name, shift traffic, and then delete the old one. (Or use delete + apply, but that causes downtime.)
Error from server (InternalError): Internal error occurred: failed calling webhook "validate.kyverno.svc": ... context deadline exceeded
Cause: The admission webhook service is unreachable or timed out.
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
kubectl get validatingwebhookconfiguration NAME -o jsonpath='{.webhooks[*].failurePolicy} {.webhooks[*].clientConfig.service}{"\n"}'
kubectl -n kyverno get pods,endpointslicesWarning: resource deployments/api is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply
Cause: The object was created with kubectl create or another tool, so it had no annotation history the first time CSA apply ran. kubectl adds it automatically, and this is usually harmless.
Recommendation: Standardize your team on kubectl apply --server-side, or add --save-config when you create objects.
Warning FailedCreate replicaset/api-7c6b9f8d5d Error creating: pods "api-7c6b9f8d5d-" is forbidden: exceeded quota: shop-quota
Cause: The Deployment and RS were written successfully, but the RS's Pod creation was rejected by a ResourceQuota (validating admission). This kind of error does not appear in the kubectl apply output. You can only see it in the RS events.
kubectl -n shop describe rs -l app.kubernetes.io/name=api | grep -A3 FailedCreate kubectl -n shop describe quota
1. Run server-side apply on api-deploy.yaml with the field manager ci-pipeline, so that it fails on conflicts.
kubectl apply --server-side --field-manager=ci-pipeline -f api-deploy.yaml
Without --force-conflicts, a conflict produces an error and a non-zero exit code.
2. Show only Warning events in the shop namespace, sorted by time.
kubectl -n shop get events --field-selector type=Warning --sort-by=.lastTimestamp
kubectl apply returns deployment.apps/api created, but 30 seconds later kubectl get pods still shows no api Pods. Following the apply journey, what would you check, in order?
A successful apply means authentication, authorization, admission, and etcd all passed. No Pods means the problem is before the Pod objects are created. ① kubectl get rs: if there is no RS, check the Deployment conditions and whether the controller-manager is healthy (in kind, use crictl ps --name kube-controller-manager). ② If there is an RS but DESIRED is 3 and CURRENT is 0, run kubectl describe rs and look for FailedCreate events. Common causes: a ResourceQuota is exceeded, PodSecurity rejects the Pod (violates PodSecurity "restricted"), a validating webhook or VAP rejects it, or the ServiceAccount doesn't exist. ③ If the Pods exist but are Pending, move on to the scheduling stage and check for FailedScheduling.
Verified video lessons
No verified official video specifically covering Server-Side Apply was found. Refer to the official docs.
Official docs
- Server-Side Apply
- Controlling Access to the Kubernetes API
- Admission Control
- Validating Admission Policy
- kube-scheduler
- Declarative Management (client-side apply)
Video storyboard script
This courseware cannot generate video or MP3 files directly, so a storyboard and narration script are provided instead.
Visual: You type kubectl apply in the terminal, and an envelope flies toward the API server.
Narration: “The moment you press Enter, kubectl just sends one HTTPS request.”
Visual: The envelope passes through five gates in turn: authentication, authorization, mutating admission, validation, and validating admission. Finally, it lands in etcd.
Narration: “It has to pass authentication, authorization, admission, and validation in turn before it is written to etcd and gets a new resource version.”
Visual: The Deployment controller creates a ReplicaSet, and the ReplicaSet creates three blank Pod cards.
Narration: “Controllers watch for new objects. The Deployment creates a ReplicaSet, and the ReplicaSet creates Pods.”
Visual: The scheduler scores the nodes and stamps lab-worker2 on the Pod cards.
Narration: “The scheduler filters and scores the nodes, then writes the node name into the Pod. This is called binding.”
Visual: The kubelet calls containerd. It starts pause first, CNI assigns the IP, and then it starts the application containers. The Pod cards turn green and join the EndpointSlice.
Narration: “The kubelet uses CRI to create the sandbox and containers. CNI assigns the address. Finally, the Pod becomes ready and joins the Service's list of backends.”
Module 6 · Namespace · Label · Selector · Annotation
- Distinguish namespaced resources from cluster-scoped resources, and know what the 4 default namespaces are for.
- Use the recommended
app.kubernetes.io/*labels. Write equality-based and set-based selectors, and use-l,-L,--show-labels, and--field-selectorfluently. - Understand that controllers claim Pods through selectors. If you change a Pod's labels, it leaves its ReplicaSet and Service.
- Know the difference between labels and annotations, and what each is for.
What: Namespace
A Namespace is a name scope and a policy boundary within a cluster. Names must be unique within a namespace. RBAC (Role/RoleBinding), ResourceQuota, LimitRange, NetworkPolicy, and Pod Security labels all apply per namespace. A Namespace is not network or security isolation by itself. By default, Pods in different namespaces can reach each other.
| Default namespaces | Purpose |
|---|---|
default | Default location when no namespace is specified. Don't use it in production. |
kube-system | System components (CoreDNS, kube-proxy, CNI, control plane static Pods) |
kube-public | Readable by everyone, including unauthenticated users. Holds bootstrap information such as the cluster-info ConfigMap |
kube-node-lease | One Lease object per node, used for node heartbeats |
kind also creates local-path-storage (storage provisioner). Cluster-scoped resources (Node, PersistentVolume, StorageClass, ClusterRole, the Namespace itself, CRDs, and so on) do not belong to any namespace: kubectl api-resources --namespaced=false.
What: Labels, Selectors, Annotations
| Labels | Annotations | |
|---|---|---|
| Purpose | Identify and select objects | Attach non-identifying metadata |
| Can be selected? | Yes (selector) | No |
| Value limits | Up to 63 characters, must start and end with an alphanumeric character, may contain -_.; prefix is optional (for example app.kubernetes.io/) | Any string; total size of all annotations ≤256KB |
| Typical examples | app.kubernetes.io/name=api, env=prod, tier=backend | kubernetes.io/change-cause, prometheus.io/scrape, build commit, owner contact, Ingress controller config |
Recommended labels (official Kubernetes set)
| Key | Example | Meaning |
|---|---|---|
app.kubernetes.io/name | api | Application name |
app.kubernetes.io/instance | api-prod | Unique instance name |
app.kubernetes.io/version | 6.17.0 | Application version (do not put it in a selector, or upgrades will change the selector) |
app.kubernetes.io/component | backend | Role in the architecture |
app.kubernetes.io/part-of | shop | Parent application |
app.kubernetes.io/managed-by | helm / kubectl / argocd | Managed by |
Why: selectors are the only link
Deployments and ReplicaSets do not store a list of “which Pods I have,” and Services also do not store a list of “which Pods I forward to.” Instead, they compute the answer each time through a label selector:
- ReplicaSet: the number of Pods matched by
spec.selectorthat no other controller owns = the actual replica count (claimed and released through ownerReferences). - Service:
spec.selectormatches Ready Pods, which the EndpointSlice controller writes into an EndpointSlice. - NetworkPolicy, PodDisruptionBudget, topologySpreadConstraints, and Pod affinity all rely on label selection.
How: selector syntax
| Type | Command line -l | YAML |
|---|---|---|
| Equality-based | app=api, env!=prod | matchLabels: {app: api} |
| Set-based | 'env in (dev,staging)', 'tier notin (db)' | matchExpressions: [{key: env, operator: In, values: [dev, staging]}] |
| Existence | team, '!canary' | operator: Exists / DoesNotExist |
| Combined | app=api,env in (prod) (comma = AND) | matchLabels and matchExpressions must both match |
Note: a Service's spec.selector supports only equality (as a map). Deployments, ReplicaSets, Jobs, and similar resources also support matchExpressions. Field selectors (--field-selector) filter by object fields instead, and only a limited set of fields is supported (for example metadata.name, metadata.namespace, status.phase, and spec.nodeName).
When: namespace strategy
- Split by team or application (shop, payments). Give each namespace its own RBAC, ResourceQuota, LimitRange, and a default-deny NetworkPolicy.
- For dev/staging/prod, separate clusters are better than separate namespaces. The control plane, nodes, CRD versions, and upgrade schedule are all shared.
Figure 6-1: Label selectors connect objects
Figure 6-2: Namespace-scoped vs cluster-scoped
Interactive 1: Change a Pod's label to detach it from the ReplicaSet
Click the “Change label” button under any Pod. It is equivalent to running kubectl label pod POD app.kubernetes.io/name=debug --overwrite. Watch how the RS controller and the EndpointSlice controller respond.
app.kubernetes.io/name=api,pod-template-hash=7c6b9f8d5d · desired 3 · matched 3Interactive 2: Selector evaluator
Enter an -l selector (supports =, ==, !=, in ( ), notin ( ), key, and !key; a comma means AND) to see which Pods match.
Core commands
| Command | Purpose | Key flags |
|---|---|---|
kubectl get ns / create ns | Namespace management | kubectl get ns --show-labels (automatic label kubernetes.io/metadata.name) |
kubectl api-resources --namespaced=false | List cluster-scoped resources | --namespaced=true |
kubectl get pods -A | All namespaces | = --all-namespaces |
-l / --selector | Filter by label | Equality, set-based, existence |
-L key1,key2 | Show label values as columns | Useful for comparing versions or environments |
--show-labels | Show all labels | |
kubectl label | Add, change, or remove labels | --overwrite; key- removes |
kubectl annotate | Add, change, or remove annotations | --overwrite; key- removes |
--field-selector | Filter by field | status.phase!=Running, spec.nodeName=lab-worker |
kubectl get ns kubectl api-resources --namespaced=false | head -12 kubectl -n shop get pods -L app.kubernetes.io/name,app.kubernetes.io/part-of kubectl -n shop get pods -l 'app.kubernetes.io/name in (api,web)' --show-labels kubectl get pods -A --field-selector spec.nodeName=lab-worker2,status.phase=Running
NAME STATUS AGE default Active 40m kube-node-lease Active 40m kube-public Active 40m kube-system Active 40m local-path-storage Active 40m shop Active 30m NAME READY STATUS RESTARTS AGE NAME PART-OF api-7c6b9f8d5d-x2k4p 1/1 Running 0 8m api shop
kubectl -n shop label deploy api app.kubernetes.io/version=6.17.0
kubectl -n shop annotate deploy api owner="team-shop@contoso.com" runbook="https://wiki.contoso.com/shop/api"
kubectl -n shop label deploy api app.kubernetes.io/version- # remove the label
kubectl -n shop get deploy api -o jsonpath='{.metadata.annotations}{"\n"}'
- How to verify:
kubectl get … --show-labels/-o jsonpath='{.metadata.labels}'. - Common error: changing an existing label without
--overwritefails with'app' already has a value (api), and --overwrite is false. - Production use: consistent recommended labels make cost allocation (grouping by part-of), monitoring aggregation, and bulk operations easier (
kubectl delete all -l app.kubernetes.io/instance=x; rungetfirst to confirm).
Lab 6: Make a Pod “run away” (about 5 minutes)
shop/api (3 replicas) from Module 5 is running. Create a temporary Service to watch the backends change:
kubectl -n shop expose deploy api --name=api-tmp --port=80 --target-port=9898 kubectl -n shop get endpointslices -l kubernetes.io/service-name=api-tmp
NAME ADDRESSTYPE PORTS ENDPOINTS AGE api-tmp-8hx2q IPv4 9898 10.244.1.6,10.244.2.5,10.244.2.6 3s
kubectl -n shop get pods -L app.kubernetes.io/name -w
POD=$(kubectl -n shop get pod -l app.kubernetes.io/name=api -o jsonpath='{.items[0].metadata.name}')
kubectl -n shop label pod $POD app.kubernetes.io/name=debug --overwrite
kubectl -n shop get pods -L app.kubernetes.io/name
kubectl -n shop get pod $POD -o jsonpath='ownerReferences={.metadata.ownerReferences}{"\n"}'
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api-tmp
NAME READY STATUS RESTARTS AGE NAME api-7c6b9f8d5d-q9v7n 1/1 Running 0 2s api ← created by the RS api-7c6b9f8d5d-x2k4p 1/1 Running 0 12m debug ← the “abandoned” Pod, still running api-7c6b9f8d5d-zz8kd 1/1 Running 0 12m api api-7c6b9f8d5d-m2h4w 1/1 Running 0 12m api ownerReferences= NAME ADDRESSTYPE PORTS ENDPOINTS AGE api-tmp-8hx2q IPv4 9898 10.244.1.6,10.244.2.6,10.244.1.9 2m
The Pod with the changed label loses its ownerReferences (it becomes an orphan) and leaves the Service backends. But it keeps running. This is the standard production technique for “isolating an unhealthy instance for forensics.”
api. The RS now sees 4 matching Pods and deletes one of them (usually the newest, or according to the ReplicaSet scale-down ordering rules):
kubectl -n shop label pod $POD app.kubernetes.io/name=api --overwrite sleep 3; kubectl -n shop get pods -l app.kubernetes.io/name=api
kubectl -n shop get pods --field-selector status.phase=Running -o name kubectl -n shop annotate deploy api kubernetes.io/change-cause="initial deploy 6.17.0" --overwrite
kubectl -n shop delete svc api-tmp (keep the api Deployment).Case 1: Isolate an unhealthy instance for forensics
Problem: one api Pod shows slowly growing memory use. You want to preserve the state and take a heap dump without affecting live traffic.
Approach: kubectl label pod api-xxx app.kubernetes.io/name=api-quarantine --overwrite. The Pod leaves the Service backends immediately, and the RS starts a healthy replacement. Then use kubectl debug or port-forward to collect evidence from it, and delete it when you're done.
Limitation: if a NetworkPolicy also allows traffic based on this label, your forensic access may be blocked. The PDB also stops counting this Pod.
Case 2: A wrong Service selector sends traffic to both blue and green
Problem: the blue and green Deployments both have the label app=api and differ only by version. The Service selector only has app=api, so traffic goes to both blue and green at the same time.
Approach: the Service selector explicitly includes a distinguishing label (app=api, slot=blue). When you switch, change only the Service's selector. Verify the backends with kubectl get endpointslices -l kubernetes.io/service-name=api -o wide.
Case 3: Namespace governance baseline
Approach: create every team namespace through GitOps with the same baseline: labels (team, cost-center, pod-security.kubernetes.io/enforce=restricted), ResourceQuota, LimitRange, a default-deny NetworkPolicy, and RoleBinding. In AKS, you can combine this with Azure Policy to require labels.
Common errors and fixes
Error from server (NotFound): deployments.apps "api" not found
Cause: the object is in a different namespace, and the default namespace in your current context is wrong.
kubectl get deploy -A | grep api
kubectl config view --minify -o jsonpath='{..namespace}{"\n"}'
kubectl config set-context --current --namespace=shoperror: 'app.kubernetes.io/name' already has a value (api), and --overwrite is false
Cause: changing an existing label requires explicit confirmation.
kubectl label pod POD app.kubernetes.io/name=debug --overwrite
The Deployment "api" is invalid: spec.template.metadata.labels: Invalid value: ...: `selector` does not match template `labels`
Cause: the Deployment's selector must match the labels on its Pod template. Otherwise, the Pods it creates won't even claim themselves.
kubectl explain deployment.spec.selector
Make sure every key-value pair in spec.selector.matchLabels also appears in spec.template.metadata.labels.
Namespace "old-team" stuck in Terminating
Cause: finalizers on some resources in the namespace can't complete (for example, a CRD's controller was uninstalled, or the metrics.k8s.io API service is unavailable).
kubectl get ns old-team -o jsonpath='{.status.conditions}' | jq
kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 kubectl get -n old-team --ignore-not-found --show-kind
kubectl get apiservices | grep FalseFirst fix the unavailable APIService or reinstall the controller so the finalizers can complete. Forcibly removing finalizers can leave orphaned cloud resources behind.
1. List Pods in all namespaces where env is prod or staging and that have no canary label. Show env as a column.
kubectl get pods -A -l 'env in (prod,staging),!canary' -L env
2. List all non-Running Pods on the lab-worker node.
kubectl get pods -A --field-selector spec.nodeName=lab-worker,status.phase!=Running
The team wants to add app.kubernetes.io/version to both the Deployment selector and the Service selector, saying “this gives precise control over versions.” Do you agree?
I disagree. ① A Deployment's spec.selector is immutable. Every version upgrade would force you to delete and recreate the Deployment, losing rolling updates and rollout history. ② If a Service has a version selector, new-version Pods are not in the backends during a rolling update while old-version Pods gradually drain. You can end up with zero backends and an outage. ③ Keep the version as a regular label or annotation (for observation, or displayed with -L). Selectors should use only stable identity labels (name, instance, component). If you need to shift traffic by version, use a separate Deployment with an explicit switch label (blue-green), or traffic weights in the Gateway API (hour 3).
Verified teaching videos
Official docs
Video storyboard
This courseware cannot generate a video or MP3 directly, so it provides a storyboard and a narration script instead.
Visual: a building divided into rooms (namespaces), with a quota and an access control at each room's door.
Narration: “A namespace is a boundary for names and policies, but it does not isolate the network by itself.”
Visual: Pods have colored labels attached. The ReplicaSet and the Service each hold a magnifying glass and search by label.
Narration: “Neither the controller nor the service keeps a list. Each time, they look for Pods using a label selector.”
Visual: one Pod's label is torn off, and the Pod walks out of the line. The ReplicaSet immediately adds a new Pod.
Narration: “Change the label, and the Pod leaves the controller and the service. The controller then creates a replacement.”
Visual: annotations look like sticky notes: owner, change reason, monitoring config.
Narration: “Annotations record information and cannot be selected. Labels identify and select.”
Module 7 · Deployments and ReplicaSets
- Understand the Deployment → ReplicaSet → Pod hierarchy and the role of
pod-template-hash. - Know how RollingUpdate (
maxSurge/maxUnavailable, both 25% by default) behaves differently from Recreate. - Be fluent with
kubectl set imageandrollout status/history/undo/restart/pause/resume. Record the reason for each change with thekubernetes.io/change-causeannotation. - Understand what
revisionHistoryLimit,progressDeadlineSeconds, andminReadySecondsdo, and be able to diagnose a “stuck” rollout.
What: the hierarchy and pod-template-hash
A Deployment manages multiple ReplicaSets. Each RS corresponds to one version of the Pod template. The Deployment controller computes a hash of spec.template and adds it as the pod-template-hash label to the RS's selector and to the Pod template, so the selectors of different RS versions never overlap. Only changes to spec.template (image, environment variables, annotations, resources, and so on) trigger a new version. Changing replicas only scales the current RS.
Deployment api ReplicaSet api-7c6b9f8d5d ← api + pod-template-hash Pod api-7c6b9f8d5d-x2k4p ← RS name + random suffix (generateName)
Why: why two levels are needed
A RS only “keeps N identical Pods.” It knows nothing about versions. The Deployment adds version management on top: it creates a new RS, gradually moves replicas from the old RS to the new one according to the strategy, and keeps the old RS (with 0 replicas) as a rollback point (revisionHistoryLimit, default 10). Rolling back means scaling the old RS back up.
How: two strategies
| Strategy | Behavior | Parameters | Use when |
|---|---|---|---|
| RollingUpdate (default) | The new RS scales up gradually while the old RS scales down. At any moment, the total Pod count is ≤ replicas + maxSurge, and the available Pod count is ≥ replicas − maxUnavailable. | maxSurge (default 25%, rounded up), maxUnavailable (default 25%, rounded down). They cannot both be 0. | Most stateless services |
| Recreate | Scale the old RS to 0 first (wait until all old Pods terminate), then create the new RS. | — | Old and new versions cannot run side by side (exclusive locks, single writer, incompatible database schema). Causes downtime. |
| replicas | maxSurge 25% | maxUnavailable 25% | Max Pods | Min available |
|---|---|---|---|---|
| 3 | ⌈0.75⌉ = 1 | ⌊0.75⌋ = 0 | 4 | 3 (no loss of availability) |
| 4 | 1 | 1 | 5 | 3 |
| 10 | ⌈2.5⌉ = 3 | ⌊2.5⌋ = 2 | 13 | 8 |
Related fields
| Field | Default | Purpose |
|---|---|---|
revisionHistoryLimit | 10 | How many old RSs to keep for rollback |
progressDeadlineSeconds | 600 | If there is no progress for longer than this, the condition Progressing=False, reason=ProgressDeadlineExceeded is set. It does not roll back automatically, but rollout status exits with a non-zero code, so CI can fail or roll back based on it. |
minReadySeconds | 0 | How many seconds a new Pod must stay Ready before it counts as available. This prevents a version that crashes right after starting from being rolled out too quickly. |
paused | false | Changing the template while paused does not trigger a rollout, so you can make several changes and roll them out together. |
When: recording the reason for a change
kubectl … --record is deprecated (don't use it with recent kubectl versions). Set the annotation kubernetes.io/change-cause when you make a change. It is copied to the matching RS and shown in the CHANGE-CAUSE column of kubectl rollout history. In GitOps setups, the Git commit history is the better source of truth.
rollout undo rolls back ConfigMaps.” No. It only rolls back the Pod template. The contents of referenced ConfigMaps and Secrets are not rolled back. (Hour 2 covers immutable ConfigMaps and name hashes.) ② “The image tag hasn't changed but the content has, so apply will trigger an update.” No. If the template hasn't changed, nothing happens. Use kubectl rollout restart (it triggers a change by setting the template annotation kubectl.kubernetes.io/restartedAt), or better, use a digest. ③ “maxUnavailable: 0 means zero downtime, always.” Not by itself. Your readiness probe also has to report readiness accurately. Otherwise, a Pod that is “Running but not ready” still counts as available. ④ “A progressDeadline timeout rolls back automatically.” It does not.Figure 7-1: Deployment → ReplicaSet → Pod (during a rolling update)
Figure 7-2: Rolling update timeline (replicas=4, maxSurge=1, maxUnavailable=1)
Rolling update simulator: podinfo 6.16.0 → 6.17.0
Adjust the replica count, maxSurge, and maxUnavailable, then click “Start upgrade” to step through it. When you choose “Bad image,” the new Pod gets stuck in ImagePullBackOff. Watch how the rollout stops at the availability floor and does not keep deleting old Pods. Then roll back with “rollout undo.”
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl set image deploy/api api=IMG | Change the container image (triggers a rollout) | Format: container-name=image. *=IMG changes all containers. |
kubectl rollout status deploy/api | Wait for the rollout to finish | --timeout; returns a non-zero exit code on timeout or failure |
kubectl rollout history deploy/api | View revision history | --revision=N shows the template for one revision |
kubectl rollout undo deploy/api | Roll back to the previous or a specified revision | --to-revision=N |
kubectl rollout restart deploy/api | Rolling restart of all Pods | Sets the restartedAt template annotation |
kubectl rollout pause/resume | Pause/resume a rollout | You can change the template several times while paused |
kubectl scale deploy/api --replicas=N | Scale up/down | Does not create a new revision |
kubectl annotate … kubernetes.io/change-cause=… | Record the reason for a change | Replaces the deprecated --record |
kubectl -n shop set image deploy/api api=ghcr.io/stefanprodan/podinfo:6.17.0 kubectl -n shop annotate deploy/api kubernetes.io/change-cause="upgrade podinfo to 6.17.0 (CHG-1024)" --overwrite kubectl -n shop rollout status deploy/api --timeout=120s kubectl -n shop rollout history deploy/api
deployment.apps/api image updated deployment.apps/api annotated Waiting for deployment "api" rollout to finish: 2 out of 4 new replicas have been updated... Waiting for deployment "api" rollout to finish: 1 old replicas are pending termination... deployment "api" successfully rolled out deployment.apps/api REVISION CHANGE-CAUSE 1 initial deploy podinfo 6.16.0 2 upgrade podinfo to 6.17.0 (CHG-1024)
kubectl -n shop get rs -l app.kubernetes.io/name=api -L pod-template-hash \ -o custom-columns='NAME:.metadata.name,DESIRED:.spec.replicas,READY:.status.readyReplicas,REV:.metadata.annotations.deployment\.kubernetes\.io/revision,IMAGE:.spec.template.spec.containers[0].image'
NAME DESIRED READY REV IMAGE api-5d8f7c9b4 0 <none> 1 ghcr.io/stefanprodan/podinfo:6.16.0 api-7c6b9f8d5d 4 4 2 ghcr.io/stefanprodan/podinfo:6.17.0
kubectl -n shop rollout undo deploy/api # roll back to the previous version (creates new revision number 3) kubectl -n shop rollout undo deploy/api --to-revision=2 kubectl -n shop rollout pause deploy/api kubectl -n shop set image deploy/api api=ghcr.io/stefanprodan/podinfo:6.17.0 kubectl -n shop set env deploy/api PODINFO_UI_MESSAGE="hello from k8s" kubectl -n shop rollout resume deploy/api # the two changes are combined into one rollout
- How to verify:
kubectl get deploy api -o jsonpath='{.status.conditions[?(@.type=="Progressing")].reason}'returnsNewReplicaSetAvailable. - Common error: a wrong container name in
set image:error: unable to find container named "podinfo". (Usespec.containers[].name. In this hour, the name isapi.) - Production use: in CI, if
kubectl rollout status --timeout=…fails, runrollout undo. Or use Argo Rollouts or Flagger for canary releases (hour 6).
Lab 7: Upgrade, get stuck, roll back (about 8 minutes)
cd ~/k8slab/m5
sed -i -e 's/replicas: 3/replicas: 4/' -e 's/podinfo:6.17.0/podinfo:6.16.0/' api-deploy.yaml
kubectl -n shop patch deploy api --type=merge -p '{"spec":{"revisionHistoryLimit":5,"progressDeadlineSeconds":90,"minReadySeconds":5,"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'
kubectl apply --server-side --force-conflicts -f api-deploy.yaml
kubectl -n shop annotate deploy/api kubernetes.io/change-cause="baseline podinfo 6.16.0" --overwrite
kubectl -n shop rollout status deploy/api
kubectl -n shop get deploy api -o jsonpath='{.spec.strategy}{"\n"}'
deployment "api" successfully rolled out
{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0},"type":"RollingUpdate"}
Note: the strategy fields are set with patch (the manager is kubectl-patch), while the image and replica count are managed by the manifest through SSA. This also shows several field managers co-managing one object.
watch -n1 'kubectl -n shop get rs,pods -l app.kubernetes.io/name=api -L pod-template-hash'
kubectl -n shop set image deploy/api api=ghcr.io/stefanprodan/podinfo:6.17.0 kubectl -n shop annotate deploy/api kubernetes.io/change-cause="upgrade to 6.17.0" --overwrite kubectl -n shop rollout status deploy/api kubectl -n shop exec deploy/api -- wget -qO- localhost:9898/version
Watch terminal A. With maxUnavailable=0, one new Pod always appears first (total 5). Only after it has been Ready for 5 seconds is one old Pod deleted. The cycle repeats 4 times.
kubectl -n shop set image deploy/api api=ghcr.io/stefanprodan/podinfo:6.17.9
kubectl -n shop annotate deploy/api kubernetes.io/change-cause="bad tag 6.17.9" --overwrite
kubectl -n shop rollout status deploy/api --timeout=120s; echo "exit=$?"
kubectl -n shop get deploy api -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}{"\n"}{end}'
Waiting for deployment "api" rollout to finish: 1 out of 4 new replicas have been updated... error: deployment "api" exceeded its progress deadline exit=1 Available=True MinimumReplicasAvailable Progressing=False ProgressDeadlineExceeded
Because maxUnavailable=0, all 4 old Pods are kept, and the service stays up. This is the value of the availability floor. Only one new Pod is stuck in ImagePullBackOff.
kubectl -n shop rollout history deploy/api kubectl -n shop rollout undo deploy/api kubectl -n shop rollout status deploy/api kubectl -n shop rollout history deploy/api
REVISION CHANGE-CAUSE 1 baseline podinfo 6.16.0 2 upgrade to 6.17.0 3 bad tag 6.17.9 deployment.apps/api rolled back deployment "api" successfully rolled out REVISION CHANGE-CAUSE 1 baseline podinfo 6.16.0 3 bad tag 6.17.9 4 upgrade to 6.17.0
A rollback is itself a “new rollout”: the revision 2 template is reactivated and numbered 4 (the original revision 2 disappears). Note that the local manifest file still says 6.16.0. After rolling back, update Git and the manifest too. Otherwise, the next apply will “change it back” again.
kubectl -n shop patch deploy api --type=merge -p '{"spec":{"strategy":{"type":"Recreate","rollingUpdate":null}}}'
kubectl -n shop rollout restart deploy/api && kubectl -n shop get pods -w
You'll see all 4 Pods Terminating at once, and only then are the new Pods created. The service is unavailable during this time. When you're done, switch back to RollingUpdate: kubectl -n shop patch deploy api --type=merge -p '{"spec":{"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'.
sed -i 's/podinfo:6.16.0/podinfo:6.17.0/' ~/k8slab/m5/api-deploy.yaml. Keep api running (used in Module 8).
kubectl set image changed the image field as field manager kubectl-set, so ownership of that field moved away from kubectl. If you then use kubectl apply --server-side to change the image to a different value, you get conflict with "kubectl-set". To take ownership back, confirm and add --force-conflicts. This is the cost of mixing imperative changes with declarative management.Case 1: Release gates and automatic rollback
Problem: the pipeline reports success right after kubectl apply, but a bad version went live and wasn't noticed for 20 minutes.
Approach: set progressDeadlineSeconds (for example, 300) + minReadySeconds (for example, 10) + an accurate readiness probe. In the pipeline:
kubectl apply --server-side --field-manager=ci -f k8s/ if ! kubectl -n shop rollout status deploy/api --timeout=320s; then kubectl -n shop rollout undo deploy/api kubectl -n shop rollout status deploy/api --timeout=320s exit 1 fi
Limitation: this only catches “won't start” or “not ready” problems. Business metric regressions need canary analysis (Argo Rollouts or Flagger).
Case 2: Rollout speed for a service with many replicas
Problem: a 200-replica service uses the default 25%/25%, so 50 Pods are replaced at once. Pulling images saturates node bandwidth instantly, and downstream connection pools become unstable.
Approach: set limits based on spare capacity: maxSurge: 10% and maxUnavailable: 0. Pre-warm images (pre-pull with a DaemonSet or use a node image cache). Use a PodDisruptionBudget to protect availability during node maintenance.
Case 3: Re-pushing the same tag causes a “deployed but nothing changed” problem
Problem: the team keeps pushing the same tag, api:prod. After apply, the Pods don't change. Some nodes run the old content because of imagePullPolicy: IfNotPresent, and others run the new content.
Approach: use an immutable tag (git SHA) or a digest for every build (the Docker course covered this). Only template changes trigger a rollout, and that is what makes rollback history meaningful.
Common errors and fixes
error: deployment "api" exceeded its progress deadline
Cause: the new RS's Pods can't become Ready: wrong image, crashes, failed probes, Pending due to insufficient resources, or quota rejection.
kubectl -n shop get rs -l app.kubernetes.io/name=api kubectl -n shop describe rs $(kubectl -n shop get rs -l app.kubernetes.io/name=api --sort-by=.metadata.creationTimestamp -o name | tail -1 | cut -d/ -f2) | tail -10 kubectl -n shop get pods -l app.kubernetes.io/name=api --sort-by=.metadata.creationTimestamp | tail -3 kubectl -n shop rollout undo deploy/api
Waiting for deployment "api" rollout to finish: 0 of 4 updated replicas are available... (no progress for a long time)
Cause: the new Pod is Running but not Ready (readiness probe failing), or it is stuck in Pending (insufficient resources).
kubectl -n shop get pods -l app.kubernetes.io/name=api -o wide kubectl -n shop describe pod POD | grep -E 'Readiness|FailedScheduling|Insufficient'
Deployment.apps "api" is invalid: spec.strategy.rollingUpdate.maxUnavailable: Invalid value: intstr.IntOrString{...}: may not be 0 when `maxSurge` is 0
Cause: maxSurge and maxUnavailable can't both be 0. Otherwise, no replacement can happen.
Set at least one of them to a non-zero value. For zero-downtime rollouts, use maxSurge: 1, maxUnavailable: 0.
After a rollback, the bad version comes back
Cause: GitOps or CI is still applying a manifest that contains the bad version. The source of the cluster's desired state has not changed.
kubectl -n shop get deploy api -o yaml --show-managed-fields | grep -E 'manager:|time:'
Revert the commit in Git, or pause automatic sync and then roll back.
1. Check which image the second revision of the api Deployment uses.
kubectl -n shop rollout history deploy/api --revision=2 | grep -i image
2. Without changing any image, restart all api Pods once using the rolling strategy, and wait for it to finish.
kubectl -n shop rollout restart deploy/api && kubectl -n shop rollout status deploy/api
replicas=10, default strategy. You release a version that crashes 30 seconds after starting (no readiness probe is configured, and minReadySeconds=0). What happens? How do you prevent it?
Without a readiness probe, a container counts as Ready as soon as it starts. With minReadySeconds=0, it counts as available immediately. The Deployment moves forward at 25% (surge 3 / unavailable 2), so it may replace every Pod within 30 seconds. Then all the new Pods start crashing and enter CrashLoopBackOff. The service suffers a large outage, while rollout status has already reported success. To avoid this: ① configure an accurate readiness probe (and a startup probe); ② set minReadySeconds (for example, 45, which is longer than the window between startup and crash), so the controller watches for a while before continuing; ③ reduce maxSurge/maxUnavailable; ④ use canary releases with metric analysis; ⑤ if you spot the problem, run rollout undo immediately.
Verified teaching videos
Official docs
Video storyboard
This courseware cannot generate a video or MP3 directly, so it provides a storyboard and a narration script instead.
Visual: three layers of blocks: the Deployment on top, two ReplicaSets in the middle, and Pods at the bottom. The RS name suffixes are highlighted.
Narration: “A Deployment manages multiple ReplicaSets. Each ReplicaSet corresponds to one version of the Pod template.”
Visual: green new Pods appear one by one, and gray old Pods disappear one by one. A counter at the top shows the total and available counts.
Narration: “During a rolling update, you can have at most maxSurge extra Pods and at most maxUnavailable fewer Pods. The rollout continues only after the new Pods are ready.”
Visual: the bad-image Pod turns red, the progress bar stops, and the progressDeadlineSeconds countdown reaches zero.
Narration: “If the new version won't start, the rollout stops. After the timeout, it is marked as failed, but it does not roll back automatically.”
Visual: you type kubectl rollout undo, and the old ReplicaSet scales back up.
Narration: “Rolling back means scaling the previous version's ReplicaSet back up. It's fast.”
Module 8 · Service basics and basic troubleshooting
- Understand the problem a Service solves: Pod IPs change → a stable ClusterIP + DNS name + load balancing.
- Distinguish ClusterIP and NodePort (and LoadBalancer, covered in hour 3). Be clear on
port/targetPort/nodePort. - Understand the chain from selector → EndpointSlice → kube-proxy rules, and how the DNS name
api.shop.svc.cluster.localis resolved. - Be able to use
kubectl expose,port-forward svc/api, and a temporary busybox Pod to test connectivity. Troubleshoot with the decision tree: Pod Pending, ImagePullBackOff, CrashLoopBackOff, Service with no endpoints, DNS not working, and kubectl can't connect.
What: Service types
| Type | How to access | Implementation | Use |
|---|---|---|---|
| ClusterIP (default) | Inside the cluster: api.shop.svc.cluster.local:80 or the ClusterIP | Virtual IP allocated from the Service CIDR (10.96.0.0/16 in kind). kube-proxy writes DNAT rules on every node. | Service-to-service calls |
| NodePort | <any node IP>:30080 | Builds on ClusterIP. Every node opens the same port in the 30000–32767 range. | Labs, and backends for a self-managed load balancer |
| LoadBalancer | Public or internal IP of a cloud load balancer | Builds on NodePort. cloud-controller-manager creates a cloud LB (AKS: Azure Load Balancer). | External exposure (hour 3, with the Gateway API) |
Headless (clusterIP: None) | DNS returns the list of Pod IPs directly | No virtual IP, no kube-proxy rules | StatefulSets (hours 2 and 4) |
| ExternalName | DNS CNAME to an external domain | DNS only | Reference an external service during a migration |
Three ports
apiVersion: v1
kind: Service
metadata:
name: api
namespace: shop
spec:
type: NodePort
selector:
app.kubernetes.io/name: api # must match the Pod template labels
ports:
- name: http
port: 80 # port on the Service (ClusterIP): clients access api.shop:80
targetPort: http # port on the Pod: a number such as 9898, or the container port name http (recommended, since changing the port doesn't require changing the Service)
nodePort: 30080 # port opened on each node (if omitted, it is assigned automatically); kind-lab.yaml already maps it to VM 127.0.0.1:30080
protocol: TCP
Why: why a Service is needed
Modules 1, 6, and 7 showed that Pods get deleted, recreated, and replaced during rolling updates, and their IPs change each time. Clients can't track Pod IPs. A Service provides a stable virtual IP and DNS name. Its backends are chosen dynamically by the selector and include only Ready Pods, so rolling updates and self-healing are transparent to clients.
How: the chain
- EndpointSlice controller (in controller-manager) watches Services and Pods. It writes the IP, port,
conditions.ready, node, and zone of each Pod matched by the selector into an EndpointSlice. Each slice holds up to 100 endpoints by default, with the labelkubernetes.io/service-name=api. The legacy v1 Endpoints API has been deprecated since v1.33. It can still be read, but it shows a warning. - kube-proxy (on every node) watches Services and EndpointSlices and writes iptables or nftables rules. Packets addressed to ClusterIP:port or NodeIP:nodePort are DNATed to the IP:targetPort of a ready backend Pod (iptables mode chooses one at random).
- CoreDNS watches Services and EndpointSlices, and serves A/AAAA records (pointing to the ClusterIP) and SRV records for
<svc>.<ns>.svc.cluster.local. The kubelet sets each Pod's/etc/resolv.conftonameserver 10.96.0.10(the kube-dns Service), withsearch shop.svc.cluster.local svc.cluster.local cluster.localandoptions ndots:5.
| Accessed from | Names you can use |
|---|---|
| Pods in the same namespace (shop) | api, api.shop, api.shop.svc.cluster.local |
| Pods in other namespaces | api.shop or the full FQDN |
| VM / outside the cluster | NodePort, LoadBalancer, kubectl port-forward (ClusterIPs and cluster DNS are not available outside the cluster) |
When: choosing an access method
- Service-to-service calls: ClusterIP + DNS name.
- Development and debugging:
kubectl port-forward svc/api 8080:80(tunnels through the apiserver directly to one Pod. It skips kube-proxy and does no load balancing). - External access: LoadBalancer or Gateway/Ingress (hour 3). Exposing NodePort directly is rarely used in production.
wget/curl/nc. ② “If port-forward works, the Service is fine.” port-forward doesn't go through the Service selector or kube-proxy. ③ “Services do health checks.” A Service doesn't probe anything itself. It relies on the Pods' readiness status. ④ “You can write any targetPort.” It must be the port the container actually listens on (9898 for podinfo). Otherwise, the endpoints exist but connections are refused.Figure 8-1: Service → EndpointSlice → Pod
Figure 8-2: NodePort path in kind
Step-by-step animation: wget -qO- http://api.shop/ from DNS to Pod
The client is a temporary busybox Pod on lab-worker. Below, you can toggle the readiness of a backend Pod and watch how the EndpointSlice and kube-proxy rules respond.
Core commands
| Command | Purpose | Key flags |
|---|---|---|
kubectl expose deploy/api | Quickly create a Service from a Deployment's selector | --port --target-port --type --name --dry-run=client -o yaml |
kubectl create service nodeport | Create a Service template | --tcp=80:9898 --node-port=30080 (the selector is app=name, which you usually need to change) |
kubectl get svc,endpointslices | View a Service and its backends | -l kubernetes.io/service-name=api, -o wide |
kubectl port-forward svc/api 8080:80 | Local debugging access | Selects one backend Pod, no load balancing |
kubectl run tmp --rm -it --image=busybox:1.37 -- sh | Temporary debugging Pod inside the cluster | --restart=Never; deleted automatically on exit |
kubectl get events --sort-by=.lastTimestamp | Troubleshooting timeline | --field-selector type=Warning |
kubectl -n shop expose deploy api --name=api --port=80 --target-port=9898 --type=ClusterIP kubectl -n shop get svc api -o wide kubectl -n shop get endpointslices -l kubernetes.io/service-name=api
service/api exposed NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR api ClusterIP 10.96.143.21 <none> 80/TCP 2s app.kubernetes.io/name=api NAME ADDRESSTYPE PORTS ENDPOINTS AGE api-x7k2p IPv4 9898 10.244.1.6,10.244.2.5,10.244.2.6 2s
kubectl -n shop run tmp --rm -it --image=busybox:1.37 --restart=Never -- sh # inside tmp: cat /etc/resolv.conf nslookup api for i in 1 2 3 4 5 6; do wget -qO- http://api/ | grep hostname; done
search shop.svc.cluster.local svc.cluster.local cluster.local nameserver 10.96.0.10 options ndots:5 Server: 10.96.0.10 Address: 10.96.0.10:53 Name: api.shop.svc.cluster.local Address: 10.96.143.21 "hostname": "api-7c6b9f8d5d-x2k4p", "hostname": "api-7c6b9f8d5d-m2h4w", "hostname": "api-7c6b9f8d5d-x2k4p", "hostname": "api-7c6b9f8d5d-zz8kd", ...
busybox's nslookup may also print NXDOMAIN lookups for the search domains. This is normal with ndots:5. Note that backends are reassigned randomly only for new connections. A long-lived HTTP keep-alive connection stays on the same Pod.
kubectl -n shop patch svc api -p '{"spec":{"type":"NodePort","ports":[{"port":80,"targetPort":9898,"nodePort":30080,"protocol":"TCP"}]}}'
curl -s 127.0.0.1:30080/version # via kind extraPortMappings
kubectl -n shop port-forward svc/api 8080:80 &
curl -s localhost:8080/healthz; kill %1
docker exec lab-worker iptables -t nat -L KUBE-SERVICES -n | grep shop/api docker exec lab-worker iptables -t nat -S | grep -E 'KUBE-SEP.*DNAT' | grep 9898
KUBE-SVC-XXXXXXXXXXXXXXXX tcp -- 0.0.0.0/0 10.96.143.21 /* shop/api cluster IP */ tcp dpt:80 -A KUBE-SEP-AAAA... -p tcp -m comment --comment "shop/api" -m tcp -j DNAT --to-destination 10.244.1.6:9898 -A KUBE-SEP-BBBB... -p tcp -m comment --comment "shop/api" -m tcp -j DNAT --to-destination 10.244.2.5:9898
- How to verify: the ENDPOINTS column of the EndpointSlice is not empty, and the IPs match
kubectl get pods -o wide. - Common error: using
busybox:latestas the busybox image tag gets rejected by policy on restricted clusters. This hour pinsbusybox:1.37(verified on Docker Hub). - Production use: Service names serve as dependency addresses in config (
DB_HOST=db.shop.svc.cluster.local). Temporary debugging Pods are used to troubleshoot DNS and ports.
Lab 8: Expose api and complete one troubleshooting exercise (about 8 minutes)
mkdir -p ~/k8slab/m8 && cd ~/k8slab/m8
kubectl -n shop delete svc api --ignore-not-found
cat > api-svc.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
name: api
namespace: shop
labels:
app.kubernetes.io/name: api
spec:
type: NodePort
selector:
app.kubernetes.io/name: api
ports:
- name: http
port: 80
targetPort: http
nodePort: 30080
EOF
kubectl apply --server-side -f api-svc.yaml
kubectl -n shop get svc,endpointslices -l app.kubernetes.io/name=api
kubectl -n shop get endpointslices -l kubernetes.io/service-name=apicurl -s 127.0.0.1:30080/ | grep -E 'hostname|version' # NodePort (on the VM) kubectl -n shop port-forward svc/api 8080:80 >/dev/null & sleep 1 curl -s localhost:8080/version; kill %1 # port-forward kubectl -n shop run tmp --rm -i --image=busybox:1.37 --restart=Never -- wget -qO- http://api.shop.svc.cluster.local/healthz # in-cluster DNS
To open it in your local browser: ssh -L 30080:127.0.0.1:30080 azureuser@VM_IP, then open http://localhost:30080 to see the podinfo UI.
kubectl -n shop patch svc api -p '{"spec":{"selector":{"app.kubernetes.io/name":"apl"}}}'
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api
curl -s -m 3 127.0.0.1:30080/ || echo "Connection failed"
# Diagnose: compare the Service selector with the Pod labels
kubectl -n shop get svc api -o jsonpath='{.spec.selector}{"\n"}'
kubectl -n shop get pods --show-labels | head -3
kubectl apply --server-side --force-conflicts -f api-svc.yaml # fix
NAME ADDRESSTYPE PORTS ENDPOINTS AGE api-x7k2p IPv4 <unset> <unset> 5m Connection failed
kubectl -n shop patch svc api --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8080}]'
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api # has IPs, port 8080
kubectl -n shop run tmp --rm -i --image=busybox:1.37 --restart=Never -- wget -qO- -T 3 http://api/ ; echo
kubectl apply --server-side --force-conflicts -f api-svc.yaml # fix
wget: can't connect to remote host (10.96.143.21): Connection refused
kubectl -n shop scale deploy api --replicas=0 && sleep 3 kubectl -n shop get endpointslices -l kubernetes.io/service-name=api kubectl -n shop scale deploy api --replicas=3 && kubectl -n shop rollout status deploy/api
Case 1: Occasional 502 errors during a rolling update
Problem: the frontend calls api through a Service. Each release causes a small number of 502s and connection resets.
Approach: when a Pod is deleted, “removal from the EndpointSlice → kube-proxy updates rules on each node” and “kubelet sends SIGTERM” happen in parallel, so the rule update may lag behind. Fixes: a readiness probe + graceful shutdown in the application (keep handling in-flight requests after receiving SIGTERM) + a short sleep in lifecycle.preStop. Newer versions also provide a native sleep lifecycle action, which works with distroless images (check the official docs for its feature stage). Also set terminationGracePeriodSeconds to be longer than the preStop time plus the shutdown time.
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 5"]
terminationGracePeriodSeconds: 30
Case 2: DNS query amplification
Problem: the application accesses the external domain api.partner.com. Because of ndots:5 (fewer than 5 dots in the name), it first tries the 3 search domains in turn. CoreDNS query volume is several times what you'd expect, and timeouts occur.
Approach: use a fully qualified domain name with a trailing dot for external domains (api.partner.com.), or set ndots: 2 in the Pod's dnsConfig. Scale out CoreDNS or enable NodeLocal DNSCache. Watch the CoreDNS metrics.
Case 3: Choosing Service types in AKS
Approach: use ClusterIP only for internal services. When you need access from inside the VNet, use an internal LoadBalancer with service.beta.kubernetes.io/azure-load-balancer-internal: "true". Route public entry points through the Gateway API (hour 3). In AKS, NodePort requires NSG rules and node IPs aren't stable, so it isn't recommended for external use.
Interactive basic troubleshooting decision tree
Choose by symptom, step by step, to get the diagnostic commands and fixes. Covers: kubectl can't connect, Pod Pending, ImagePullBackOff, CrashLoopBackOff, Service with no endpoints, and DNS not working.
Common errors
wget: bad address 'api.shop' / nslookup: can't resolve
Cause: the Service name or namespace is wrong; CoreDNS is unhealthy; or the Pod uses dnsPolicy: Default (which doesn't use cluster DNS).
kubectl get svc -A | grep api kubectl -n kube-system get pods -l k8s-app=kube-dns kubectl -n kube-system logs -l k8s-app=kube-dns --tail=20 kubectl run tmp --rm -it --image=busybox:1.37 --restart=Never -- nslookup kubernetes.default
Service exists, but ENDPOINTS is <unset> / empty
Cause: the selector matches no Pods; the matching Pods are all not Ready; or the Pods are in a different namespace (a Service only selects Pods in its own namespace).
kubectl -n shop get svc api -o jsonpath='{.spec.selector}{"\n"}'
kubectl -n shop get pods -l app.kubernetes.io/name=api -o wide
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api -o yaml | grep -A3 conditionsThe Service "api" is invalid: spec.ports[0].nodePort: Invalid value: 30080: provided port is already allocated
Cause: the NodePort must be unique across the cluster, and it is already used by another Service; or it is outside the 30000–32767 range.
kubectl get svc -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {.spec.ports[*].nodePort}{"\n"}{end}' | grep 30080error: unable to forward port because pod is not running. Current status=Pending
Cause: port-forward svc/api picked a backend Pod that is not running.
kubectl -n shop get pods -l app.kubernetes.io/name=api kubectl -n shop describe pod POD | sed -n '/Events/,$p'
1. Generate the YAML for a ClusterIP Service for the shop/api Deployment (port 80 → 9898). Don't create it directly.
kubectl -n shop expose deploy api --port=80 --target-port=9898 --dry-run=client -o yaml
2. List all backend Pod IPs for the api Service (use the EndpointSlice).
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{" ready="}{.conditions.ready}{"\n"}{end}'A web Pod calling http://api:80 gets Connection refused, but kubectl port-forward pod/api-xxx 9898:9898 works fine. Analyze the likely causes and the order in which to troubleshoot them.
A working port-forward means the Pod and the application itself are fine. The problem is in the Service path. ① Name resolution: Connection refused means the name resolved to an IP and reached something. First confirm it resolves to the ClusterIP of api.shop. (Is web in the shop namespace? If not, use api.shop.) ② Service port: is port 80? ③ targetPort: does it match the container's listening port, 9898? (A common mistake is writing 8080.) A refusal often means targetPort is wrong. ④ EndpointSlice: are there ready endpoints? (If it's empty, kube-proxy in iptables mode answers with REJECT for a Service with no endpoints, which also looks like “refused.”) ⑤ Check for a NetworkPolicy (hour 3). Commands: kubectl get svc api -o yaml, kubectl get endpointslices -l kubernetes.io/service-name=api, and wget -T3 http://api.shop/ from a temporary busybox.
Verified teaching videos
Official docs
Video storyboard
This courseware cannot generate a video or MP3 directly, so it provides a storyboard and a narration script instead.
Visual: the IPs of three Pods keep flickering and changing, and the client looks confused.
Narration: “Pod addresses can change at any time. Clients need a stable entry point.”
Visual: a Service sign shows the ClusterIP and DNS name. Behind it, the EndpointSlice list grows and shrinks with Pod readiness.
Narration: “A Service provides a fixed virtual address and name. The backend list is maintained automatically, based on the selector and readiness.”
Visual: a packet arrives at the ClusterIP, and kernel rules rewrite it to a Pod IP.
Narration: “The rules in each node's kernel do the forwarding. kube-proxy writes them.”
Visual: decision tree: Pending, image pull failure, repeated crashes, no backends, DNS not working.
Narration: “When troubleshooting, check the Pod status first, then the events and logs. Finally, check the service's backends and DNS.”
Command cheat sheet
Cluster and context
kubectl version; kubectl cluster-info kubectl config get-contexts kubectl config use-context kind-lab kubectl config set-context --current --namespace=shop kubectl config view --minify kubectl auth whoami; kubectl auth can-i --list -n shop kubectl get --raw '/readyz?verbose' kubectl api-resources [--namespaced=false] [--api-group=apps] kubectl api-versions kubectl explain deploy.spec.strategy --recursive
View resources
kubectl get all -n shop kubectl get pods -A -o wide kubectl get pods -l app.kubernetes.io/name=api -L pod-template-hash kubectl get pods --show-labels kubectl get pods --field-selector status.phase!=Running -A kubectl get pods -w --output-watch-events kubectl describe pod|deploy|svc|node NAME kubectl get events --sort-by=.lastTimestamp [-w] kubectl get events --field-selector type=Warning kubectl get nodes -o wide; kubectl describe node NODE
Pod
kubectl run NAME --image=IMG [--port=P] [-l k=v] [--restart=Never]
kubectl logs POD [-c C] [--previous] [-f] [--tail=50] [--since=10m]
kubectl logs -l app.kubernetes.io/name=api --all-containers --prefix
kubectl exec -it POD [-c C] -- sh
kubectl port-forward pod/POD 8080:9898
kubectl cp POD:/path ./local
kubectl delete pod POD [--wait=false] [--grace-period=0 --force]
kubectl get pod POD -o jsonpath='{.status.containerStatuses[0].lastState}'Deployment
kubectl create deploy api --image=IMG --replicas=3 --port=9898 --dry-run=client -o yaml kubectl apply --server-side [--field-manager=ci] -f FILE kubectl diff -f FILE kubectl set image deploy/api api=IMG kubectl annotate deploy/api kubernetes.io/change-cause="…" --overwrite kubectl rollout status deploy/api --timeout=120s kubectl rollout history deploy/api [--revision=N] kubectl rollout undo deploy/api [--to-revision=N] kubectl rollout restart|pause|resume deploy/api kubectl scale deploy/api --replicas=5
Service
kubectl expose deploy api --port=80 --target-port=9898 [--type=NodePort] kubectl get svc,endpointslices -n shop kubectl get endpointslices -l kubernetes.io/service-name=api -o wide kubectl port-forward svc/api 8080:80 kubectl run tmp --rm -it --image=busybox:1.37 --restart=Never -- sh # nslookup api.shop ; wget -qO- -T3 http://api.shop/
Debugging
kubectl debug -it POD --image=busybox:1.37 --target=CONTAINER kubectl debug POD -it --copy-to=POD-dbg --container=app -- sh kubectl debug node/lab-worker -it --image=busybox:1.37 kubectl get pod POD -o yaml --show-managed-fields kubectl get deploy api -v=8 kubectl proxy --port=8001 & curl localhost:8001/api/v1/namespaces/shop/pods docker exec lab-worker crictl ps -a docker exec lab-worker journalctl -u kubelet -n 50 --no-pager
Output formats
-o wide | -o yaml | -o json | -o kyaml | -o name
-o jsonpath='{.items[*].metadata.name}'
-o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'
-o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,IMAGE:.spec.containers[0].image'
--sort-by=.metadata.creationTimestamp
-o json | jq -r '.items[] | select(.status.phase!="Running") | .metadata.name'kind
kind create cluster --name lab --config kind-lab.yaml kind get clusters; kind get nodes --name lab kind get kubeconfig --name lab kind load docker-image my/app:1.0 --name lab # load a local image into the nodes kind export logs ./kind-logs --name lab docker exec -it lab-control-plane bash kind delete cluster --name lab
Quick troubleshooting table
| Symptom (STATUS) | What to do first | Common causes |
|---|---|---|
Pending | kubectl describe pod and look for FailedScheduling | Insufficient resources (Insufficient cpu/memory), taints not tolerated, nodeSelector mismatch, PVC not bound |
ErrImagePull / ImagePullBackOff | The message of the Failed event in describe | Tag doesn't exist, no credentials for a private registry, network/proxy |
CrashLoopBackOff | logs --previous, lastState.terminated | Application error (exit 1), OOMKilled (137), command not found (127), liveness probe failure |
CreateContainerConfigError | The Error line in describe | ConfigMap/Secret or key does not exist |
Running but 0/1 | Check the Readiness events in describe | Readiness probe failure (hour 2) |
| Service not reachable | get endpointslices -l kubernetes.io/service-name=X | selector mismatch, Pods not ready, wrong targetPort |
| DNS not working | nslookup kubernetes.default from a temporary busybox | CoreDNS problems, wrong name/namespace |
| Stuck rollout | rollout status, describe of the new RS | New version Pods can't become Ready; progressDeadlineSeconds exceeded |
connection refused (kubectl) | docker ps, config current-context | kind nodes stopped, wrong context |
For the full interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.
Recommended config snippet: skeleton of a production-ready Deployment (hour 2 fills in probes and resources)
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: shop
labels: { app.kubernetes.io/name: api, app.kubernetes.io/part-of: shop }
annotations:
kubernetes.io/change-cause: "release 6.17.0 (CHG-1024)"
spec:
replicas: 3
revisionHistoryLimit: 5
progressDeadlineSeconds: 300
minReadySeconds: 5
strategy:
type: RollingUpdate
rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
selector:
matchLabels: { app.kubernetes.io/name: api } # use only stable identity labels
template:
metadata:
labels: { app.kubernetes.io/name: api, app.kubernetes.io/part-of: shop, app.kubernetes.io/version: "6.17.0" }
spec:
terminationGracePeriodSeconds: 30
containers:
- name: api
image: ghcr.io/stefanprodan/podinfo:6.17.0 # in production, use an @sha256 digest
ports: [{ name: http, containerPort: 9898 }]
Capstone lab + final quiz
shop namespace. Inside the cluster, it is reached through api.shop.svc.cluster.local (ClusterIP). On the VM, verify it through NodePort 30080. All changes must be declarative (files + kubectl apply --server-side). If a release fails, there must be zero downtime and a fast rollback. Keep the cluster after the lab for use in hour 2.kubectl config use-context kind-lab
kubectl -n shop delete deploy,svc --all # delete the api objects and others from module exercises (keep the namespace)
mkdir -p ~/k8slab/final && cd ~/k8slab/final
cat > 00-namespace.yaml <<'EOF'
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
app.kubernetes.io/part-of: shop
EOFcat > 10-api-deploy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: shop
labels: { app.kubernetes.io/name: api, app.kubernetes.io/part-of: shop }
annotations:
kubernetes.io/change-cause: "v1: podinfo 6.16.0"
spec:
replicas: 3
revisionHistoryLimit: 5
progressDeadlineSeconds: 60
minReadySeconds: 5
strategy:
type: RollingUpdate
rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
selector:
matchLabels: { app.kubernetes.io/name: api }
template:
metadata:
labels: { app.kubernetes.io/name: api, app.kubernetes.io/part-of: shop }
spec:
containers:
- name: api
image: ghcr.io/stefanprodan/podinfo:6.16.0
command: ["./podinfo"]
args: ["--port=9898", "--ui-message=shop api v1"]
ports: [{ name: http, containerPort: 9898 }]
EOF
cat > 20-api-svc.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
name: api
namespace: shop
labels: { app.kubernetes.io/name: api }
spec:
type: ClusterIP
selector: { app.kubernetes.io/name: api }
ports: [{ name: http, port: 80, targetPort: http }]
---
apiVersion: v1
kind: Service
metadata:
name: api-nodeport
namespace: shop
labels: { app.kubernetes.io/name: api }
spec:
type: NodePort
selector: { app.kubernetes.io/name: api }
ports: [{ name: http, port: 80, targetPort: http, nodePort: 30080 }]
EOF
kubectl apply --server-side -f . --dry-run=server
kubectl diff -f . ; echo "diff exit=$?"
kubectl apply --server-side -f .
kubectl -n shop rollout status deploy/api
The podinfo image only defines CMD ["./podinfo"] (working directory /home/app, no ENTRYPOINT). In Kubernetes, command overrides ENTRYPOINT and args overrides CMD. So if you only write args, --port=9898 gets treated as the executable. You must also write command here. --ui-message is shown on the podinfo home page and in the JSON at / (the message field).
kubectl -n shop get deploy,rs,pods,svc,endpointslices -o wide curl -s 127.0.0.1:30080/ | grep -E '"(hostname|version|message)"' kubectl -n shop run tmp --rm -i --image=busybox:1.37 --restart=Never -- \ sh -c 'for i in 1 2 3 4 5 6; do wget -qO- http://api.shop.svc.cluster.local/ | grep hostname; done'
"hostname": "api-5d8f7c9b4-k2v8x", "message": "shop api v1", "version": "6.16.0",
sed -i -e 's/podinfo:6.16.0/podinfo:6.17.0/' -e 's/shop api v1/shop api v2/' -e 's/"v1: podinfo 6.16.0"/"v2: podinfo 6.17.0"/' 10-api-deploy.yaml kubectl diff -f 10-api-deploy.yaml kubectl apply --server-side -f 10-api-deploy.yaml kubectl -n shop rollout status deploy/api kubectl -n shop rollout history deploy/api while true; do curl -s 127.0.0.1:30080/version | grep version; sleep 0.5; done # Run this in a second terminal during the upgrade to confirm there is no downtime. Press Ctrl+C to stop.
kubectl -n shop delete pod -l app.kubernetes.io/name=api --wait=false kubectl -n shop get pods -w # Watch 3 new Pods get created. Press Ctrl+C. kubectl -n shop get events --sort-by=.lastTimestamp | grep -E 'SuccessfulCreate|Scheduled' | tail -6 # Optional: simulate a node failure (Pods are only evicted and recreated after about 5 minutes; see module 1, case 1) # docker stop lab-worker2 ; kubectl get nodes -w ; docker start lab-worker2
cp 10-api-deploy.yaml 10-api-deploy.yaml.good
sed -i -e 's/podinfo:6.17.0/podinfo:6.17.9/' -e 's/"v2: podinfo 6.17.0"/"v3: bad tag"/' 10-api-deploy.yaml
kubectl apply --server-side -f 10-api-deploy.yaml
kubectl -n shop rollout status deploy/api --timeout=90s || {
echo "== Release failed, start troubleshooting =="
kubectl -n shop get pods -l app.kubernetes.io/name=api
kubectl -n shop get events --field-selector type=Warning --sort-by=.lastTimestamp | tail -5
kubectl -n shop get deploy api -o jsonpath='{.status.conditions[?(@.type=="Progressing")].reason}{"\n"}'
echo "== Declarative rollback: restore the previous file from Git =="
cp 10-api-deploy.yaml.good 10-api-deploy.yaml
kubectl apply --server-side -f 10-api-deploy.yaml
kubectl -n shop rollout status deploy/api
}
curl -s 127.0.0.1:30080/version | grep version
error: deployment "api" exceeded its progress deadline == Release failed, start troubleshooting == NAME READY STATUS RESTARTS AGE api-6b8d9c7f5-q7w2e 0/1 ImagePullBackOff 0 62s api-7c6b9f8d5d-4hx9s 1/1 Running 0 4m ... Warning Failed pod/api-6b8d9c7f5-q7w2e Failed to pull image "ghcr.io/stefanprodan/podinfo:6.17.9": ... not found ProgressDeadlineExceeded == Declarative rollback: restore the previous file from Git == deployment.apps/api serverside-applied deployment "api" successfully rolled out "version": "6.17.0"
For comparison, kubectl rollout undo can also roll back, but it leaves the cluster out of sync with the files. In a GitOps workflow, a revert commit is the source of truth (simulated here by restoring the file). Throughout, maxUnavailable=0 keeps the 3 old Pods serving traffic.
kubectl -n shop delete svc api-nodeport # Hour 2 redesigns external access. Keep the api Deployment and ClusterIP Service rm -f 10-api-deploy.yaml.good kubectl -n shop get all # Not continuing today: az vm deallocate -g rg-k8s-lab -n vm-k8s (after the VM starts, run docker start lab-control-plane lab-worker lab-worker2 to start the kind containers) # Done for good: kind delete cluster --name lab
Open-ended self-check (answer first, then expand the reference answers)
1. Explain Kubernetes' “control loop” in one sentence, and give one example observed in this hour.
Controllers continuously watch the desired and actual state of objects in the API. When they find a difference, they act to make the two match. Example: after a Pod is deleted, the ReplicaSet controller receives a DELETED event from its watch, computes 2 < 3, and creates a new Pod.
2. Why is kube-apiserver called the “hub” of the cluster? What happens if it becomes unavailable?
Only the API server accesses etcd, and all components coordinate only through its REST and watch interfaces. When it is unavailable, running containers and forwarding rules that were already written usually keep working. However, all changes, scheduling, self-healing, and scaling stop, and kubectl stops working too.
3. What does it mean when kubectl apply returns success? What doesn't it mean?
It means the request passed authentication, authorization, admission, and validation, and was written to etcd. It does not mean the Pod has been scheduled, the image has been pulled, or the container is ready. These steps are asynchronous, so confirm them with rollout status and events.
4. How do two containers in one Pod communicate? Why can't different Pods use localhost?
Containers in the same Pod share the network namespace held by the pause container and communicate via localhost:port. Different Pods each have their own network namespace and IP, so they must be reached through the Pod IP or a Service name.
5. How does a Service know which Pods to send traffic to?
Through a label selector. The EndpointSlice controller writes the matching Pods that are Ready into an EndpointSlice. kube-proxy then writes DNAT rules on each node based on it. CoreDNS resolves the Service name to a ClusterIP.
6. In a rolling update, what are the effects and trade-offs of maxSurge=1 and maxUnavailable=0?
Effect: at any time, the number of available Pods is at least replicas, so a stuck bad version does not affect the existing service. Trade-off: you need spare capacity for one extra Pod, and the rollout is slower because only one Pod is replaced at a time.
Final quiz (12 questions, covering all modules)
Sources and versions
| Topic | Verification result | Source |
|---|---|---|
| Supported Kubernetes versions | 1.37 (latest patch 1.37.1, 2026-09-15; EOL 2027-10-28), 1.36, and 1.35 are supported. 1.34 reaches EOL on 2026-10-27. 1.38 is planned for around 2026-12. | kubernetes.io/releases (accessed 2026-11-15) |
| v1.37 release highlights | “Garhwal”, 2026-08-26; KYAML (-o kyaml) GA; metrics.k8s.io GA; kube-proxy ipvs deprecated (use nftables); kube-dns deprecated; kubectl run -f deprecated; cgroup v1 being phased out | Kubernetes v1.37 release blog (2026-08-26) |
| Other GA history | Native sidecars v1.33 GA; kube-proxy nftables v1.33 GA; ValidatingAdmissionPolicy v1.30 GA; ephemeral containers v1.25 GA; kubelet failCgroupV1 defaults to true since v1.35 | Sidecar Containers · Virtual IPs and Service Proxies · VAP |
| Components | Responsibilities of control plane and node components, add-ons | Kubernetes Components · Cluster Architecture |
| Pod lifecycle | Five phase values, three container states, restartPolicy, CrashLoopBackOff back-off (starts at 10s, doubling, capped at 5 minutes) | Pod Lifecycle |
| Deployment | RollingUpdate defaults maxSurge/maxUnavailable 25%; revisionHistoryLimit defaults to 10; progressDeadlineSeconds defaults to 600; kubernetes.io/change-cause | Deployments |
| Service / EndpointSlice / DNS | Service types, NodePort range 30000–32767, EndpointSlice label kubernetes.io/service-name; v1 Endpoints API deprecated since v1.33; DNS name format and ndots:5 | Service · EndpointSlices · DNS for Services and Pods |
| Server-Side Apply | managedFields, conflicts and --force-conflicts, application/apply-patch+yaml | Server-Side Apply |
| kubectl installation | pkgs.k8s.io is organized by minor version (core:/stable:/v1.37/deb/); binary download and sha256 verification; version skew ±1 | Install kubectl on Linux |
| kind | v0.33.0 (2026-08-26); default node image kindest/node:v1.37.0@sha256:a1ed56cf…; pinning the digest is recommended; known inotify issue; extraPortMappings | kind releases · Known Issues · Configuration |
| Sample app image | podinfo 6.16.0 and 6.17.0 are both published (6.17.0 is the latest); busybox:1.37 exists on Docker Hub (last updated 2026-10-28) | podinfo releases · Docker Hub busybox (accessed 2026-11-15) |
| AKS | The control plane is managed and not visible; 1.37 reached GA in 2026-10 (following the course's unified convention) | AKS supported Kubernetes versions |
Video verification notes
All video links were checked through the YouTube oEmbed API. For each one, the video ID, title and channel match (2026-11-15): Fireship, “Kubernetes Explained in 100 Seconds” (PziYflu8cB8); TechWorld with Nana, “What is Kubernetes | Kubernetes explained in 15 mins” (VnvRFRk_51k), “Kubernetes Architecture explained | Kubernetes Tutorial 15” (umXEmn3cMWY), “Kubectl Basic Commands … | Kubernetes Tutorial 18” (azuwXALfyRg), “Kubernetes YAML File Explained … | Kubernetes Tutorial 19” (qmDzcu5uY1I), “Complete Application Deployment using Kubernetes Components | Kubernetes Tutorial 20” (EQNO_kM96Mo), “Kubernetes Namespaces Explained in 15 mins | Kubernetes Tutorial 21” (K3jNo4z5Jx8), “Kubernetes Services explained | ClusterIP vs NodePort vs LoadBalancer vs Headless Service” (T4Z7visMM4E), “Kubernetes Crash Course for Absolute Beginners [NEW]” (s_o8dwzRlu4), “Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]” (X48VuDVv0do; a third-party index shows a runtime of 3:36:55 and a 2020-11-06 date); CNCF channel, Carson Anderson, “Kubernetes Deconstructed” (90kZRyPcRZw); IBM Technology, “Kubernetes Explained” (aSrqRSk43lY); CultRepo, “Kubernetes: The Documentary [PART 1]” (BE77h7dmoQU) / [PART 2] (318elIq37PE); Deis, Inc., “The Illustrated Children's Guide to Kubernetes” (4ht22ReBjno); NetworkChuck, “you need to learn Kubernetes RIGHT NOW!!” (7bA0gTroJjw). Unless noted otherwise, the exact runtime and publish date could not be verified, so the cards show only an approximate runtime or none. All of these videos are in English, and most were recorded before v1.30, so follow this hour and the official docs for version details. No verifiable high-quality Chinese-language Kubernetes video was found, and no verifiable official video covering Server-Side Apply or native sidecars was found.
Voice narration notes
The “Voice” tab uses the browser Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time. English terms are pronounced in en-US. The result depends on the voices installed on your operating system (for example Microsoft Zira or David on Windows, Samantha on macOS). This course-generation environment cannot reach a TTS service, so there are no embedded MP3 files. For offline audio, send the narration script to a TTS service such as Azure AI Speech. The “Video” tab in each module provides a storyboard script that you can give to a video generation tool.
Known limitations
- IP addresses, ports (such as the apiserver's 127.0.0.1:41234), UIDs, pod-template-hash values, Pod name suffixes, times, and container IDs in the “Expected output” are sample values. Use your own environment as the reference.
- The log format of
kubectl -v=8changes a lot between kubectl versions (newer versions use structured logs), so this hour shows only the key fields. - For the kind node OS, containerd minor version, and CoreDNS version, the actual contents of the kind v0.33.0 node image are authoritative.
- The timing and request order in the animations are simplified illustrations of the real mechanisms (for example, scheduling and startup of multiple Pods actually happen concurrently). They are not benchmark data.
- This hour does not give specific version numbers for features such as MutatingAdmissionPolicy and the native preStop sleep action. Check the official docs for their version.
- Azure VM costs are order-of-magnitude estimates. Use the Azure pricing calculator for exact figures.