Use a local kind or minikube cluster (a multi-node kind cluster for the advanced ones). Do each assignment in its own namespace so you can delete it cleanly. Try before opening the hints.
๐ข Beginner
A1. Your first Pod ๐ข
Objective: Create, inspect and delete a Pod, and read its lifecycle.
Tasks
- Run an
nginx:1.27Pod namedwebin namespacea1. - Show its IP, node and status with one command.
- Read its logs and exec into it to run
nginx -v. - Describe it and find the event that shows the image being pulled.
- Delete it and confirm it is gone.
Expected outcome: You can explain every field in kubectl describe pod output, and the Pod does not come back after deletion.
Hints
kubectl create ns a1, kubectl -n a1 run web --image=nginx:1.27, kubectl -n a1 get pod web -o wide. Events are at the bottom of describe. A bare Pod is not recreated because nothing owns it.
Bonus: Generate the YAML with --dry-run=client -o yaml, add a label, and apply it from a file.
A2. Deployment and scaling ๐ข
Objective: Run a Deployment and scale it.
Tasks
- Create a Deployment
hellowith 3 replicas ofnginx:1.27. - Scale it to 5, then to 2 using
kubectl scale. - Delete one Pod and watch the controller replace it.
- Show the ReplicaSet that owns the Pods.
Expected outcome: Pod count always converges to the desired replicas. You can name the owner chain Deployment, ReplicaSet, Pod.
Hints
kubectl create deploy hello --image=nginx:1.27 --replicas=3. Use kubectl get pods -w in a second terminal. kubectl get pod <name> -o jsonpath='{.metadata.ownerReferences[0].kind}'.
Bonus: Make a Pod stop being managed by changing its labels so it no longer matches the selector, then observe what happens.
A3. Expose with a Service ๐ข
Objective: Reach Pods through ClusterIP and NodePort Services.
Tasks
- Expose
hellofrom A2 as a ClusterIP Service on port 80. - From a temporary Pod,
curlthe Service by short name and by FQDN. - Change the Service type to NodePort and reach it from your machine.
- Show the EndpointSlice and match its IPs to the Pod IPs.
Expected outcome: Curl succeeds from inside the cluster by DNS name, and endpoint IPs equal the Pod IPs.
Hints
kubectl expose deploy hello --port=80. FQDN is hello.<ns>.svc.cluster.local. On kind, NodePort is reachable on the node container IP (docker inspect) or use kubectl port-forward.
Bonus: Remove the label from one Pod and watch it disappear from the EndpointSlice.
A4. Declarative YAML ๐ข
Objective: Manage resources from files, not imperative commands.
Tasks
- Write
deploy.yamlwith a Deployment, andsvc.yamlwith a Service. - Apply them, then change replicas in the file and re-apply.
- Use
kubectl diffbefore applying a change to the image tag. - Delete everything using the same files.
Expected outcome: The files are the source of truth; kubectl diff shows the change before you apply it.
Hints
kubectl apply -f ., kubectl diff -f deploy.yaml, kubectl delete -f .. Put --- between documents if you combine them into one file.
Bonus: Validate manifests without a cluster using kubectl apply --dry-run=server and then try kubeconform.
A5. ConfigMap as env and file ๐ข
Objective: Inject configuration two ways and see the difference.
Tasks
- Create a ConfigMap with keys
GREETINGandapp.properties. - Inject
GREETINGas an env var and mountapp.propertiesas a file in a busybox Pod. - Edit the ConfigMap. Observe which of the two changes inside the running Pod.
- Restart the Pod and observe again.
Expected outcome: The mounted file updates after about a minute, the env var does not change until restart.
Hints
kubectl create cm app --from-literal=GREETING=hi --from-file=app.properties. Use envFrom or valueFrom.configMapKeyRef. kubectl exec ... cat /etc/app/app.properties. Mounts with subPath never update.
Bonus: Make the ConfigMap immutable and try to edit it.
A6. Secrets ๐ข
Objective: Handle Secrets and understand what protection they do and do not give.
Tasks
- Create a Secret
dbwithusernameandpasswordusing--from-literal. - Decode the password from
kubectl get secret -o yaml. - Mount the Secret as a read-only volume and consume one key as an env var in another Pod.
- Create a
kubernetes.io/dockerconfigjsonSecret withkubectl create secret docker-registryand reference it inimagePullSecrets.
Expected outcome: You can state that base64 is not encryption and name two mitigations (encryption at rest, external secret manager, tight RBAC).
Hints
kubectl get secret db -o jsonpath='{.data.password}' | base64 -d. Volume mounts of Secrets are tmpfs-backed on the node.
Bonus: Write an RBAC Role that allows reading ConfigMaps but not Secrets and prove it with auth can-i.
A7. Namespaces, labels and selectors ๐ข
Objective: Organize and query resources.
Tasks
- Create namespaces
devandstagingand run the same Deployment in both. - Label Pods with
app,tier,env. - Query with
-l env=dev,-l 'tier in (web,api)'and--field-selector status.phase=Running. - Set a default namespace in your kubeconfig context and verify with
kubectl config view --minify. - Apply a ResourceQuota to
devlimiting Pods to 5, then try to exceed it.
Expected outcome: The sixth Pod is rejected with exceeded quota.
Hints
kubectl config set-context --current --namespace=dev. Quota: kubectl create quota q --hard=pods=5 -n dev. A Deployment will show the quota error in the ReplicaSet events.
Bonus: Add a LimitRange that sets default requests and limits, then create a Pod without resources and inspect what it got.
A8. Probes basics ๐ข
Objective: See what liveness and readiness actually do.
Tasks
- Deploy a Pod whose readiness probe is
exec: cat /tmp/readyand liveness probe ishttpGeton port 80. - Observe that the Pod is
0/1 Readyuntil youtouch /tmp/readyinside it. - Confirm a not-ready Pod is absent from the Service endpoints.
- Break liveness (point to a wrong path) and watch the restart count and events.
Expected outcome: Readiness failure removes the Pod from endpoints without restarting it. Liveness failure restarts the container.
Hints
Look for Readiness probe failed and Liveness probe failed: HTTP probe failed with statuscode: 404 in kubectl describe pod. Check RESTARTS column.
Bonus: Add a startupProbe and explain why it is better than a long initialDelaySeconds.
A9. Resource requests and limits ๐ข
Objective: Observe scheduling by requests and enforcement by limits.
Tasks
- Deploy a Pod requesting 100m CPU and 64Mi memory with limits of 200m and 128Mi.
- Check its QoS class.
- Run a memory hog (for example
polinux/stresswith--vm-bytes 200M) with a 128Mi limit and observeOOMKilled. - Request more CPU than any node has and read the
Pendingreason.
Expected outcome: You see Last State: Terminated, Reason: OOMKilled, Exit Code: 137 and Insufficient cpu in scheduling events.
Hints
kubectl get pod -o jsonpath='{.status.qosClass}'. kubectl describe node shows allocatable and allocated requests. Command for stress: stress --vm 1 --vm-bytes 200M --vm-hang 1.
Bonus: Set requests equal to limits and confirm the QoS class becomes Guaranteed.
A10. Jobs and CronJobs ๐ข
Objective: Run batch work correctly.
Tasks
- Create a Job that prints the date and exits.
- Create a Job with
completions: 5andparallelism: 2and watch it run. - Create a CronJob that runs every minute with
concurrencyPolicy: Forbid. - Set
ttlSecondsAfterFinishedandsuccessfulJobsHistoryLimitso old Jobs clean themselves up. - Trigger the CronJob manually.
Expected outcome: Completed Pods are retained until TTL, and old Jobs do not accumulate.
Hints
kubectl create job manual --from=cronjob/<name>. Set restartPolicy: OnFailure or Never (Always is invalid for Jobs). backoffLimit controls retries.
Bonus: Make a Job fail on purpose and observe backoff delays and the BackoffLimitExceeded condition.
๐ก Intermediate
A11. Rolling update and rollback ๐ก
Objective: Control rollout speed and recover from a bad release.
Tasks
- Deploy 4 replicas with
maxSurge: 1andmaxUnavailable: 0. - Update the image and watch the ReplicaSets trade replicas.
- Update to a nonexistent tag and observe the stuck rollout.
- Roll back and view
rollout history. - Set
progressDeadlineSeconds: 60and confirm the Deployment reportsProgressDeadlineExceeded.
Expected outcome: Available replicas never drop below 4 during the good rollout, and rollback restores the previous image.
Hints
kubectl rollout status, kubectl rollout undo --to-revision=N, kubectl get rs -w. Check kubectl get deploy -o jsonpath='{.status.conditions}'.
Bonus: Use kubectl rollout pause, make two changes, then resume for a single rollout.
A12. StatefulSet with persistent storage ๐ก
Objective: Prove stable identity and storage.
Tasks
- Deploy a 3-replica StatefulSet with a headless Service and a
volumeClaimTemplatesentry of 1Gi. - Write the hostname into a file on each replica's volume.
- Delete
web-1and confirm it returns with the same name and the same data. - Resolve
web-0.<headless-svc>from another Pod. - Scale down to 1 and check that PVCs for scaled-down Pods remain.
Expected outcome: Names are web-0..2, ordered start and stop, data persists, PVCs are retained after scale-down.
Hints
kubectl get pvc, nslookup web-0.web. Set podManagementPolicy: Parallel to see the difference. Retention behavior is controlled by persistentVolumeClaimRetentionPolicy.
Bonus: Expand a PVC from 1Gi to 2Gi (needs allowVolumeExpansion: true on the StorageClass).
A13. Ingress with host and path routing ๐ก
Objective: Route HTTP traffic to two services.
Tasks
- Install ingress-nginx on a kind cluster with port mappings.
- Deploy two apps (for example
hashicorp/http-echowith different text). - Route
app.localtest.me/blueandapp.localtest.me/greento them. - Add a second host
admin.localtest.meto a third service. - Add an annotation to rewrite
/blueto/at the backend.
Expected outcome: Each path and host returns the right app, and unknown hosts return the default 404.
Hints
Use ingressClassName: nginx. Rewrite needs a capture group: path: /blue(/|$)(.*) with pathType: ImplementationSpecific and nginx.ingress.kubernetes.io/rewrite-target: /$2.
Bonus: Add TLS with a self-signed certificate and force an HTTPS redirect.
A14. RBAC for a developer ๐ก
Objective: Grant least privilege and prove it.
Tasks
- Create namespace
team-aand a ServiceAccountdev. - Write a Role that can get, list, watch pods and pod logs, and exec into pods, but nothing else.
- Bind it with a RoleBinding.
- Prove each allowed and denied action with
kubectl auth can-i --as. - Build a kubeconfig that uses a token from
kubectl create tokenand test it.
Expected outcome: The user can read logs and exec in team-a but cannot read Secrets or touch other namespaces.
Hints
Resources: pods, pods/log, pods/exec (exec needs create). kubectl auth can-i --list --as=system:serviceaccount:team-a:dev -n team-a.
Bonus: Replace the Role with a ClusterRole bound by RoleBindings in two namespaces and explain why that is cleaner.
A15. HPA with CPU load ๐ก
Objective: Autoscale a workload under load.
Tasks
- Install metrics-server (with
--kubelet-insecure-tlson kind). - Deploy a CPU-bound app with a CPU request of 100m.
- Create an HPA at 50% CPU, min 1, max 8.
- Generate load and record replica count over time.
- Stop the load and observe scale-down timing.
- Tune
behavior.scaleUpandbehavior.scaleDownpolicies.
Expected outcome: Replicas rise under load and fall after the stabilization window (default 300 s).
Hints
kubectl autoscale deploy x --cpu-percent=50 --min=1 --max=8. <unknown> targets mean missing requests or metrics-server problems. Load: kubectl run -it load --image=busybox -- sh -c 'while :; do wget -qO- http://x; done'.
Bonus: Add a memory metric and explain why scaling on memory is usually a poor fit.
A16. NetworkPolicy default deny ๐ก
Objective: Isolate a namespace and open only what is required.
Tasks
- Use a CNI that enforces policy (Calico or Cilium on kind).
- Deploy
frontend,api,dbPods with labels. - Apply a default-deny for ingress and egress.
- Allow DNS egress, frontend to api, and api to db only.
- Prove allowed and blocked paths with
nc -zv -w 3.
Expected outcome: Only the two intended paths work. frontend to db times out.
Hints
An empty podSelector: {} selects all Pods. Egress to DNS needs UDP and TCP 53 to kube-dns in kube-system. A policy applies in both directions only if you allow both the egress on the source and the ingress on the destination.
Bonus: Restrict egress to an external CIDR using ipBlock with an except range.
A17. Scheduling with taints, affinity and spread ๐ก
Objective: Control where Pods land.
Tasks
- Label two kind workers
disk=ssdanddisk=hdd. - Use
nodeSelectorto pin a Pod tossd. - Taint one worker
dedicated=batch:NoScheduleand deploy a Pod with a matching toleration. - Add
podAntiAffinityso replicas avoid the same node. - Use
topologySpreadConstraintswithmaxSkew: 1overkubernetes.io/hostname.
Expected outcome: Pods land exactly where the rules say, and an impossible rule produces Pending with a clear scheduling reason.
Hints
kubectl taint nodes <n> dedicated=batch:NoSchedule. Remove with the trailing -. A toleration allows scheduling there; it does not force it, pair it with a nodeSelector or affinity.
Bonus: Compare requiredDuringScheduling... with preferredDuringScheduling... using 4 replicas and 3 nodes.
A18. PodDisruptionBudget and node drain ๐ก
Objective: Keep availability during maintenance.
Tasks
- Run a 3-replica Deployment spread over workers.
- Create a PDB with
minAvailable: 2. - Drain a worker with
kubectl drain --ignore-daemonsets --delete-emptydir-data. - Make the drain block by setting
minAvailable: 3, and read the message. - Uncordon the node.
Expected outcome: Drain evicts Pods one at a time respecting the PDB, and a too-strict PDB blocks it with Cannot evict pod as it would violate the pod's disruption budget.
Hints
kubectl get pdb shows ALLOWED DISRUPTIONS. A PDB with minAvailable equal to replicas permanently blocks drains, which is a classic upgrade outage.
Bonus: Use maxUnavailable: 1 instead and explain why it scales better with replica count.
A19. Init containers, sidecars and shared volumes ๐ก
Objective: Compose multi-container Pods.
Tasks
- Write a Pod with an init container that downloads or generates a file into an
emptyDir. - The main container serves that file with nginx.
- Add a sidecar that tails an access log from a shared volume.
- Make the init container fail and read the Pod status.
- Convert the sidecar to a native sidecar (init container with
restartPolicy: Always).
Expected outcome: Main container starts only after init succeeds, a failing init shows Init:CrashLoopBackOff, and the native sidecar starts before and stops after the main container.
Hints
kubectl logs pod -c <container>. Init logs: -c <init-name>. Native sidecars are GA from Kubernetes 1.33; on older clusters the feature gate is on by default since 1.29.
Bonus: Run a Job with a sidecar and explain why native sidecars fix the "Job never completes" problem.
A20. Debug a broken app ๐ก
Objective: Diagnose five injected faults using only kubectl.
Tasks Apply a manifest you wrote with these deliberate bugs, then fix each one.
- A Deployment with an image tag typo.
- A Service whose selector does not match Pod labels.
- A Pod with a memory limit too low (
OOMKilled). - A readiness probe on the wrong port.
- A Pod referencing a ConfigMap key that does not exist.
Write down the symptom, the command that found it, and the fix for each.
Expected outcome: All five resolved, each with a one-line root cause.
Hints
Order of attack: get pods, describe pod, logs --previous, get endpointslices, get events --sort-by=.lastTimestamp. Config errors show CreateContainerConfigError.
Bonus: Debug a distroless container with kubectl debug -it pod/x --image=busybox --target=app.
๐ด Advanced
A21. Production-ready Helm chart ๐ด
Objective: Package an app with sane defaults and safe upgrades.
Tasks
- Create a chart with
helm createand strip it to Deployment, Service, Ingress, HPA, PDB and ServiceAccount. - Make requests, limits, replicas, probes and ingress host configurable in
values.yaml. - Add
values.schema.jsonthat rejects a missing image tag. - Add a pre-upgrade Job hook for a migration.
- Run
helm lint,helm template | kubeconform, andhelm upgrade --install --atomic. - Force a failed upgrade and watch
--atomicroll back.
Expected outcome: Bad values fail at lint or install time, a failed upgrade restores the previous release.
Hints
helm history, helm rollback. Add a checksum annotation of the ConfigMap to the Pod template so config changes roll the Pods: checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}.
Bonus: Publish the chart to an OCI registry with helm push and install it from there.
A22. Admission policy and Pod Security ๐ด
Objective: Enforce guardrails at the API.
Tasks
- Label a namespace with Pod Security
enforce=restrictedand attempt to run a root Pod. Read the rejection. - Fix a Deployment to pass
restricted(non-root, no privilege escalation, drop ALL, seccomp RuntimeDefault). - Write a
ValidatingAdmissionPolicy(CEL) that rejects Deployments without resource limits. - Add a binding with
validationActions: [Deny]scoped to one namespace. - Test with a compliant and a non-compliant manifest.
Expected outcome: Violations are rejected at apply time with a clear message and compliant workloads run.
Hints
pod-security.kubernetes.io/enforce=restricted. Use warn and audit first in real clusters. ValidatingAdmissionPolicy is GA in 1.30, expression example: object.spec.template.spec.containers.all(c, has(c.resources.limits)).
Bonus: Run the same rule in Kyverno or OPA Gatekeeper and compare the authoring experience.
A23. GitOps with Argo CD or Flux ๐ด
Objective: Make Git the only way changes reach the cluster.
Tasks
- Install Argo CD (or Flux) on kind.
- Create a Git repo with app manifests in
apps/and an Application pointing at it with automated sync,pruneandselfHeal. - Change replicas in Git and watch it sync.
- Change replicas with
kubectl scaleand watch drift get reverted. - Break the manifest in Git and use
git revertto recover. - Add a second environment using Kustomize overlays.
Expected outcome: Cluster state always converges to Git. Manual drift is reverted within minutes.
Hints
Argo CD initial admin password: kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 -d. For Flux: flux bootstrap github. Use argocd app diff to see drift.
Bonus: Add Argo CD sync waves so a database migration Job runs before the Deployment.
A24. Cluster upgrade rehearsal ๐ด
Objective: Practice a minor version upgrade without downtime.
Tasks
- Create a kubeadm or kind cluster at version N-1 with 2 workers.
- Deploy an app with PDB, 3 replicas and a load generator measuring errors.
- Run
kubectl get --raw /metrics | grep apiserver_requested_deprecated_apisand scan manifests withplutoorkubentfor deprecated APIs. - Upgrade the control plane, then each worker one at a time using cordon, drain, upgrade, uncordon.
- Record error rate and any Pod restarts.
- Write the rollback plan: what can and cannot be undone (etcd snapshot).
Expected outcome: Zero failed requests during the upgrade, version skew policy respected, written runbook.
Hints
kubelet may be up to three minor versions older than the API server (since 1.28) but never newer. Take an etcd snapshot first: etcdctl snapshot save. Upgrade one minor version at a time.
Bonus: Repeat the upgrade the managed way on EKS (control plane, then managed node group rolling update) and compare.
A25. Multi-tenant platform slice ๐ด
Objective: Give two teams safe, isolated, cost-aware access to one cluster.
Tasks
- Create namespaces
team-aandteam-bfrom a template (Kustomize or Helm). - In each, apply ResourceQuota, LimitRange, default-deny NetworkPolicy, and Pod Security
baselineorrestricted. - Create RBAC: team admins in their namespace only, read-only cluster-wide for a platform viewer.
- Dedicate a node pool to team-b with a taint and a label, and enforce it with a mutating or validating policy.
- Prove isolation: team-a cannot read team-b Secrets, reach team-b Pods, or schedule onto team-b nodes.
- Document how you would bill each team (labels, requests, OpenCost).
Expected outcome: A test script that proves each isolation boundary passes, and a README explaining the model.
Hints
kubectl auth can-i get secrets -n team-b --as=... . Namespaces are not a hard security boundary; mention sandboxed runtimes (gVisor, Kata) or separate clusters for untrusted tenants. Consider the Hierarchical Namespace Controller or Capsule.
Bonus: Add a per-team ClusterQueue with Kueue, or per-team vCluster, and compare the isolation level.