Skip to content
devops/architect
02 kubernetes 01 01 kubernetes
0/8 read · lab 0/1
Module 02
// kubernetes

Kubernetes — Container Orchestration at Scale

From Pod scheduling internals and eBPF networking to RBAC hardening, HPA, and production multi-node clusters. Learn on Kind locally, graduate to EKS on AWS.

Startup SME Enterprise Killercoda CKA SadServers Udemy

Lesson objective

What it teaches
Under-The-Hood Architecture & Networking · Core Components & Objects · WSL Hands-On Lab · Real-World Project: 3-Tier App · Troubleshooting & Disaster Recovery · Interactive Lab Checklist · Cluster Metrics and Logs: metrics-server, kubectl top, /var/log/pods
Why it matters
A required lesson for DevOps Engineer, SRE, Platform Engineer, DevSecOps Engineer, Container/Kubernetes Engineer, Release / CI-CD Engineer, FinOps / Cloud Optimization, DevOps / Platform Architect, MLOps / LLMOps Engineer, Observability Engineer. Recommended for Cloud Engineer. See the role paths
What you demonstrate
  • Simulated lab: Create the cluster (takes ~2 min): Run kind create cluster --config kind-cluster.yaml --name devops-lab. Recorded as lab evidence.
  • Predict 3 results this lesson prints. You mark each one yourself.
  • Optional, real environment: 6 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue

Under-The-Hood Architecture & Networking 01

Control Plane → Data Plane Flow

When you run kubectl apply -f deployment.yaml, here's the exact journey your manifest takes through the Kubernetes control plane before a Pod lands on a Node.

API Server → etcd → Scheduler → kubelet flow
  1. API Server validation: kubectl sends a POST to /apis/apps/v1/namespaces/default/deployments. API server authenticates (x509/OIDC), runs admission webhooks (mutating → validating), validates the schema.
  2. etcd persistence: API server writes the Deployment object to etcd. etcd uses Raft consensus — the write is committed when a quorum of etcd members acknowledges it.
  3. Deployment Controller: watches for new Deployment objects via API server's watch stream, creates ReplicaSet objects to match spec.replicas.
  4. ReplicaSet Controller: creates Pod objects in Pending state. Pods have no nodeName assigned yet.
  5. Scheduler: watches for Pending Pods. Runs Filtering (which nodes can run this pod?) and Scoring (which node is best?) phases. Writes the chosen nodeName to the Pod object via a binding.
  6. kubelet on target node: watches for Pods assigned to its node. Calls the container runtime (containerd → runc) to pull the image and start containers. Updates Pod status back to API server.
CNI Networking: Calico VXLAN vs Cilium eBPF
Calico (VXLAN/IP-in-IP)
Calico uses a routed architecture. The local Felix agent programs IP routing tables on the host. In VXLAN mode, packets are encapsulated in UDP (port 4789) adding ~50 bytes of header, reducing effective MTU to ~1450. Increases CPU due to kernel-space encap/decap.
Cilium (eBPF Direct Routing)
Cilium replaces iptables by inserting eBPF programs into Linux kernel TC hooks. When a Pod transmits, Cilium bypasses the kernel network stack entirely, looks up the endpoint in a BPF map, and redirects directly to the destination. Result: bare-metal speeds, full 1500 MTU.
kube-proxy: IPTables O(N) vs IPVS O(1)
ModeLookup ComplexityMax ServicesLoad Balancing Algorithms
IPTablesO(N) — sequential rules~5,000 before degradationRandom, Round-Robin only
IPVSO(1) — hash table lookups100,000+LeastConn, SourceHash, DNAT, WRR
CoreDNS & Headless Services

CoreDNS uses a pipeline: health → errors → cache → kubernetes → forward.

  • Standard Services: Returns a single A record → ClusterIP → iptables/IPVS routes to a pod.
  • Headless Services (clusterIP: None): Returns A records directly mapping to all backing Pod IPs. Used for StatefulSets (Cassandra, Kafka, Elasticsearch).
  • SRV records: Headless services also emit SRV records for named ports — essential for service discovery protocols like gRPC.

Control Plane Architecture Diagram

graph TD subgraph CP["Control Plane (Master Node)"] API["kube-apiserver\n(REST + Watch API)"] ETCD["etcd\n(Distributed KV Store)"] SCHED["kube-scheduler\n(Filter + Score)"] CM["controller-manager\n(Deployment/RS/Node controllers)"] end subgraph N1["Worker Node 1"] KL1["kubelet"] KP1["kube-proxy (IPVS)"] CR1["containerd → runc"] P1["Pod A"] P2["Pod B"] end subgraph N2["Worker Node 2"] KL2["kubelet"] KP2["kube-proxy (IPVS)"] CR2["containerd → runc"] P3["Pod C"] end USER["kubectl apply"] -->|"HTTPS + Auth"| API API <-->|"Raft consensus"| ETCD API -->|"Watch stream"| CM CM -->|"Creates Pods"| API API -->|"Binds nodeName"| SCHED SCHED -->|"Watch Pending Pods"| API API -->|"Watch bound Pods"| KL1 API -->|"Watch bound Pods"| KL2 KL1 -->|"Runs"| CR1 CR1 --> P1 CR1 --> P2 KL2 --> CR2 CR2 --> P3 KP1 -->|"Programs IPVS rules"| P1 KP2 -->|"Programs IPVS rules"| P3
Kubernetes Pod Scheduling: The Secret Dance · 85s

Core Components & Objects 02

ObjectPurposeKey FieldsBest Practice
PodSmallest deployable unit. Shares network namespace and volumes.containers, volumes, nodeSelectorNever run Pods directly — use Deployments.
DeploymentDeclarative Pod management with rolling updates and rollbacks.replicas, strategy, selectorAlways set maxSurge and maxUnavailable for zero-downtime.
StatefulSetOrdered Pod deployment with stable network identity and persistent storage.serviceName, volumeClaimTemplatesUse for databases, Kafka, Elasticsearch.
ServiceStable virtual IP (ClusterIP) for Pod discovery and load balancing.type, selector, portsUse LoadBalancer only when cloud provider provides one; prefer Ingress.
HPAHorizontal Pod Autoscaler — scales replicas based on CPU/memory/custom metrics.scaleTargetRef, minReplicas, maxReplicas, metricsCombine with KEDA for event-driven scaling (queue depth, etc.).
PVC/PVPersistent Volume Claim/Volume for durable storage beyond Pod lifecycle.storageClassName, accessModes, capacityUse dynamic provisioning (StorageClass) — avoid static PVs in production.
NetworkPolicyL3/L4 firewall rules for Pod-to-Pod communication (requires CNI support).podSelector, policyTypes, ingress, egressDefault-deny all, then allow only required paths explicitly.
RBACRole-Based Access Control for API resource permissions.Role, ClusterRole, RoleBinding, ClusterRoleBindingPrinciple of least privilege. Never use verbs: ["*"] in production.

WSL Hands-On Lab 03

Prerequisites
Run wsl-setup.sh first. This lab requires: kubectl, kind, helm, k9s. Estimated time: 60–90 minutes.

Step 1 — Create a Multi-Node Kind Cluster

kind-cluster.yaml yaml
apiVersion: kind.x-k8s.io/v1alpha4
kind: Cluster
nodes:
  - role: control-plane
    extraPortMappings:
      - containerPort: 30080
        hostPort: 8080
        protocol: TCP
  - role: worker
  - role: worker
wsl2 ~ bash
# Create the cluster (takes ~2 min)
$ kind create cluster --config kind-cluster.yaml --name devops-lab

Creating cluster "devops-lab" ...
 ✓ Ensuring node image (kindest/node:v1.29.2)
 ✓ Preparing nodes 📦 📦 📦
 ✓ Writing configuration 📜
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Joining worker nodes 🤝
Set kubectl context to "kind-devops-lab"

# Verify the cluster
$ kubectl get nodes
NAME                        STATUS   ROLES           AGE   VERSION
devops-lab-control-plane    Ready    control-plane   2m    v1.29.2
devops-lab-worker           Ready    <none>          90s   v1.29.2
devops-lab-worker2          Ready    <none>          90s   v1.29.2

# Launch k9s TUI for visual cluster management
$ k9s

Step 2 — Deploy a 3-Tier Application

namespace-rbac.yamlyaml
apiVersion: v1
kind: Namespace
metadata:
  name: three-tier-app
  labels:
    pod-security.kubernetes.io/enforce: restricted
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: backend-sa
  namespace: three-tier-app
  automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: backend-reader
  namespace: three-tier-app
rules:
  - apiGroups: [""]
    resources: ["configmaps"]
    verbs:     ["get", "list"]
backend-deployment.yamlyaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  namespace: three-tier-app
spec:
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0   # Zero-downtime rolling update
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
    spec:
      serviceAccountName: backend-sa
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 2000
      containers:
        - name: backend
          image: nginx:alpine
          ports:
            - containerPort: 8080
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          resources:
            requests: { cpu: "100m", memory: "128Mi" }
            limits:   { cpu: "500m", memory: "256Mi" }
          readinessProbe:
            httpGet: { path: /healthz, port: 8080 }
            initialDelaySeconds: 5
          livenessProbe:
            httpGet: { path: /healthz, port: 8080 }
            initialDelaySeconds: 15
service-ingress.yamlyaml
apiVersion: v1
kind: Service
metadata:
  name: backend-svc
  namespace: three-tier-app
spec:
  selector:
    app: backend
  ports:
    - port: 80
      targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: backend-ingress
  namespace: three-tier-app
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
    - host: app.local
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: backend-svc
                port: { number: 80 }
hpa.yamlyaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: backend-hpa
  namespace: three-tier-app
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: backend
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: AverageValue
          averageValue: 200Mi
Apply & verify
# Apply all manifests
$ kubectl apply -f namespace-rbac.yaml backend-deployment.yaml service-ingress.yaml hpa.yaml

# Watch pods come up
$ kubectl get pods -n three-tier-app -w

# Check HPA status
$ kubectl get hpa -n three-tier-app

# Inspect a pod's security context
$ kubectl get pod backend-xxxx -n three-tier-app -o jsonpath='{.spec.securityContext}'

# Test rollout: update image and watch rolling update
$ kubectl set image deployment/backend backend=nginx:latest -n three-tier-app
$ kubectl rollout status deployment/backend -n three-tier-app

# Rollback if needed
$ kubectl rollout undo deployment/backend -n three-tier-app

Real-World Project: 3-Tier App 04

Startup: Local Kind Cluster

You're a solo developer deploying a React frontend + Node.js API + PostgreSQL database. Total infrastructure cost: $0 (Kind on WSL2).

Startup deployment
# Deploy PostgreSQL credentials using a secured file (never literal CLI arguments)
$ install -m 0600 /dev/null secrets/pg_password.txt && printf '%s' 'pg-dev-pass-file-only' > secrets/pg_password.txt
$ kubectl create secret generic pg-secret \
    --from-file=POSTGRES_PASSWORD=secrets/pg_password.txt \
    -n three-tier-app

# Deploy using helm (bitnami postgresql chart)
$ helm repo add bitnami https://charts.bitnami.com/bitnami
$ helm install postgres bitnami/postgresql \
    --set auth.existingSecret=pg-secret \
    -n three-tier-app

# Port-forward to test locally
$ kubectl port-forward svc/backend-svc 8080:80 -n three-tier-app

Production Secret Management: External Secrets Operator (ESO)

Upstream reference: External Secrets Operator v0.10.x and Kubernetes Secrets Documentation. Command-line --from-literal arguments expose passwords in /proc/$PID/cmdline, process trees, and shell history. In production, synchronize secrets directly from an external vault (AWS Secrets Manager, HashiCorp Vault, Azure Key Vault) using the External Secrets Operator.

k8s-externalsecret.yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: pg-secret-sync
  namespace: three-tier-app
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: aws-secrets-manager
    kind: ClusterSecretStore
  target:
    name: pg-secret
    creationPolicy: Owner
  data:
    - secretKey: POSTGRES_PASSWORD
      remoteRef:
        key: production/three-tier-app/database
        property: password

SME: EKS on AWS with Terraform

You have 20 engineers. Infrastructure needs to be automated, reliable, and multi-AZ. Uses eksctl for cluster creation and Helm for application deployment.

SME — EKS deployment
# Create EKS cluster (takes ~15 min)
$ eksctl create cluster \
    --name     sme-production \
    --region   us-east-1 \
    --nodegroup-name workers \
    --node-type t3.medium \
    --nodes-min 2 \
    --nodes-max 10 \
    --managed

# Install AWS Load Balancer Controller
$ helm install aws-load-balancer-controller \
    eks/aws-load-balancer-controller \
    --set clusterName=sme-production \
    -n kube-system

# Enable IRSA for pod-level AWS permissions
$ eksctl create iamserviceaccount \
    --cluster sme-production \
    --namespace three-tier-app \
    --name backend-sa \
    --attach-policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess \
    --approve

Enterprise: Multi-Cluster + GitOps

500+ engineers across 3 regions. Each team owns a namespace. Infrastructure as Code (Terraform), GitOps (ArgoCD), policy enforcement (OPA Gatekeeper), and multi-cluster federation.

Enterprise Architecture
Hub cluster (ArgoCD + monitoring) + spoke clusters (workloads). Each team gets an ApplicationSet-managed namespace with ResourceQuotas, LimitRanges, NetworkPolicies, and OPA constraints — all provisioned automatically via GitOps.

Enterprise Policy Enforcement & Multi-Cluster GitOps

Upstream references: OPA Gatekeeper v3.18 and Argo CD ApplicationSet v2.13. Assumptions: Kubernetes v1.31, Gatekeeper admission controller deployed in gatekeeper-system, and Argo CD managing multi-cluster fleet configurations.

In large enterprises, policy-as-code validates Kubernetes manifests before admission. The following ConstraintTemplate and Constraint enforce required metadata labels on namespaces, while the ApplicationSet generates isolated team namespaces across regional clusters.

gatekeeper-policy.yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        violation[{"msg": msg, "details": {"missing_labels": missing}}] {
          provided := {label | input.review.object.metadata.labels[label]}
          required := {label | label := input.parameters.labels[_]}
          missing := required - provided
          count(missing) > 0
          msg := sprintf("Missing required enterprise labels: %v", [missing])
        }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: ns-must-have-owner
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Namespace"]
  parameters:
    labels: ["owner", "cost-center"]
argocd-applicationset.yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: team-namespaces
  namespace: argocd
spec:
  generators:
    - list:
        elements:
          - cluster: https://k8s-prod-us-east-1.internal
            namespace: payments-prod
          - cluster: https://k8s-prod-eu-west-1.internal
            namespace: payments-prod
  template:
    metadata:
      name: "{{namespace}}-base"
    spec:
      project: default
      source:
        repoURL: https://github.com/enterprise/k8s-fleet.git
        targetRevision: HEAD
        path: teams/payments
      destination:
        server: "{{cluster}}"
        namespace: "{{namespace}}"
      syncPolicy:
        automated:
          prune: true
          selfHeal: true

Troubleshooting & Disaster Recovery 05

Pod stuck in Pending state
Diagnose Pending pod
# Step 1: Describe the pod — look for Events section
$ kubectl describe pod <pod-name> -n <namespace>

# Common causes from Events:
# "0/3 nodes are available: 3 Insufficient cpu" → resource requests too high
# "no nodes matched node affinity"              → nodeSelector mismatch
# "did not match pod anti-affinity rules"       → topology constraint violation
# "PVC not bound"                               → storage class issue

# Step 2: Check node capacity
$ kubectl describe nodes | grep -A 5 "Allocated resources"

# Step 3: Check pending PVCs
$ kubectl get pvc -n <namespace>
Deployment stuck in Progressing during rollout
Diagnose stuck rollout
# Check rollout status
$ kubectl rollout status deployment/<name> -n <ns> --timeout=60s

# View ReplicaSets to see old vs new
$ kubectl get rs -n <ns>

# Check pod logs of new pods (likely failing readinessProbe)
$ kubectl logs <new-pod-name> --previous

# Emergency rollback
$ kubectl rollout undo deployment/<name> -n <ns>
Service not reachable (connection refused / timeout)
Debug Service connectivity
# Check if Service has endpoints (if NONE, label selector is wrong)
$ kubectl get endpoints <service-name> -n <ns>

# Run a debug pod to test connectivity from inside cluster
$ kubectl run debug --image=nicolaka/netshoot --rm -it -- bash
debug# curl http://<service-name>.<namespace>.svc.cluster.local
debug# nslookup <service-name>.<namespace>

# Check if NetworkPolicy is blocking traffic
$ kubectl get networkpolicies -n <ns>

Disaster Recovery: Stacked etcd Snapshot & Restore Drill

Upstream references: Kubernetes etcd Backup Task, etcd v3.5 Disaster Recovery, and AWS EKS Control Plane Architecture.

Topology Assumptions: Kubernetes v1.31 on a self-managed stacked control-plane node (kubeadm static pod architecture). etcd listens on https://127.0.0.1:2379 with PKI keys at /etc/kubernetes/pki/etcd/.

scripts/etcd-backup-restore.sh
#!/usr/bin/env bash
# Offline disaster recovery verification script; no live destructive host execution.
set -euo pipefail

# 1. Take a consistent point-in-time snapshot using etcdctl v3 API
export ETCDCTL_API=3
BACKUP_DIR="/var/lib/etcd-backup"
SNAPSHOT_PATH="${BACKUP_DIR}/etcd-snapshot-$(date +%Y%m%d%H%M).db"
mkdir -p "${BACKUP_DIR}"

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 \
  snapshot save "${SNAPSHOT_PATH}"

# 2. Verify snapshot integrity (verifies sha256 checksum, revision, and key count)
etcdctl --write-out=table snapshot status "${SNAPSHOT_PATH}"

# 3. Safe non-destructive restore to a dedicated new directory (never overwrite active /var/lib/etcd!)
RESTORE_DIR="/var/lib/etcd-restored"
etcdctl snapshot restore "${SNAPSHOT_PATH}" \
  --data-dir=/var/lib/etcd-restored \
  --initial-cluster=control-plane=https://127.0.0.1:2380 \
  --initial-cluster-token=etcd-cluster-restore-token \
  --initial-advertise-peer-urls=https://127.0.0.1:2380

# 4. Control Plane cutover (Self-Managed only):
# a. Move /etc/kubernetes/manifests/kube-apiserver.yaml away temporarily to prevent partial writes.
# b. Update hostPath volume in /etc/kubernetes/manifests/etcd.yaml to path: /var/lib/etcd-restored.
# c. Wait for kubelet to restart the etcd static pod, then restore kube-apiserver.yaml.
# d. Verify API server health: kubectl get nodes && kubectl get pods -A

Managed EKS vs. Self-Managed Control Planes: In self-managed clusters (kubeadm/bare-metal), operators own etcd quorum, disk I/O latency, TLS cert rotation, and snapshot recovery drills. In Amazon EKS (and GKE/AKS), cloud providers operate a multi-AZ etcd cluster behind an SLA. Customers cannot access port 2379, read PKI private keys, or execute etcdctl snapshot restore. EKS disaster recovery is managed at the workload layer using GitOps (re-deploying desired state from Git), Velero (backing up object metadata and persistent volume snapshots), and AWS automated backup policies.

Interactive Lab Checklist 06

Killercoda CKA Practice Labs

Open All
  • Create a 3-node Kind cluster and verify all nodes are ReadyLab
  • Deploy a Deployment with 3 replicas and verify rolling update worksLab
  • Create a Role allowing only pod listing in a specific namespace, bind to a ServiceAccountLab
  • Apply a NetworkPolicy that isolates a namespace (deny all ingress/egress by default)Lab
  • Configure HPA on a deployment and generate load to trigger auto-scalingLab
  • Debug a broken service: fix label selector mismatch causing empty EndpointsSadServers

30-Day Learning Roadmap 07

Week 1
Core Concepts
  • Pod, ReplicaSet, Deployment lifecycle
  • Services: ClusterIP, NodePort, LoadBalancer
  • ConfigMaps & Secrets
  • kubectl cheat sheet mastery
Week 2
Storage & Scheduling
  • PV/PVC/StorageClass dynamic provisioning
  • StatefulSets for databases
  • Node affinity & taints/tolerations
  • Topology Spread Constraints
Week 3
Security & Networking
  • RBAC: Roles, ClusterRoles, Bindings
  • NetworkPolicies (Calico/Cilium)
  • Pod Security Standards (restricted)
  • Ingress + TLS cert-manager
Week 4
Production Patterns
  • HPA + KEDA event-driven scaling
  • PodDisruptionBudgets
  • Multi-cluster management
  • EKS on AWS with eksctl

Cluster Metrics and Logs: metrics-server, kubectl top, /var/log/pods 08

Probes, Events and logs --previous (above) tell you about one pod. To see the cluster, you need resource metrics and a log pipeline. kubectl top reads the Metrics API, which metrics-server provides by scraping each kubelet; the HPA uses the same API. Pod logs live as files on each node, which is what a log agent ships.

Recorded from a real run of scripts/recordings/kubernetes.sh; every output below is pasted from scripts/recordings/kubernetes.out. Cover the output, predict it, then compare.

Environment: minikube v1.34.0 (Kubernetes v1.31.0, one node, Docker driver) with Argo CD installed; metrics-server v0.7.2 from minikube addons enable metrics-server. The node reports the host's CPUs and memory, and every number, pod name and uid differs per run.

recorded run
# Before metrics-server is installed
$ kubectl top nodes
error: Metrics API not available

# After enabling it: is the Metrics API registered and available?
$ kubectl get apiservice v1beta1.metrics.k8s.io -o jsonpath='{.status.conditions[0].type}={.status.conditions[0].status}'; echo
Available=True

# Node usage
$ kubectl top nodes
NAME        CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%   
da-gitops   141m         1%     1301Mi          8%        

# Heaviest pods in argocd by memory
$ kubectl top pods -n argocd --sort-by=memory | head -4
NAME                                                CPU(cores)   MEMORY(bytes)   
argocd-dex-server-5dfd67bb67-r66wk                  1m           57Mi            
argocd-repo-server-764d477ccd-sn6ls                 1m           29Mi            
argocd-server-6767446cb9-nv29w                      1m           28Mi            

# Where the kubelet keeps pod logs on the node
$ minikube -p da-gitops ssh -- sudo ls /var/log/pods | grep argocd-server
argocd_argocd-server-6767446cb9-nv29w_450d4098-2405-4d8f-9af1-54f1158ecb47

kubectl top shows current usage only, with no history: use it to spot the heavy pod, and Prometheus with kube-state-metrics and cAdvisor for trends and alerts. Compare usage with requests, because the scheduler places pods by requests, not usage. Logs are written under /var/log/pods/<namespace>_<pod>_<uid>/ and deleted with the pod, so a DaemonSet agent (Fluent Bit, Promtail, Grafana Alloy or the OpenTelemetry Collector) must tail them to Loki, Elasticsearch or CloudWatch if you want them after a crash.

Concrete Metrics Stack & Log-Agent Pipeline Installation

Upstream references: metrics-server v0.7.2 and Fluent Bit v3.2 Loki Pipeline. Assumptions: Kubernetes v1.31, namespace-scoped secret injection, and non-destructive manifest inspection.

metrics-server-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: metrics-server
  namespace: kube-system
  labels:
    k8s-app: metrics-server
spec:
  selector:
    matchLabels:
      k8s-app: metrics-server
  template:
    metadata:
      labels:
        k8s-app: metrics-server
    spec:
      serviceAccountName: metrics-server
      containers:
        - name: metrics-server
          image: registry.k8s.io/metrics-server/metrics-server:v0.7.2
          args:
            - --cert-dir=/tmp
            - --secure-port=4443
            - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
            - --kubelet-use-node-status-port
            - --metric-resolution=15s
          ports:
            - name: https
              containerPort: 4443
              protocol: TCP
          securityContext:
            readOnlyRootFilesystem: true
            runAsNonRoot: true
            runAsUser: 10001
fluent-bit-logging.yaml
apiVersion: v1
kind: Secret
metadata:
  name: loki-credentials
  namespace: logging
type: Opaque
stringData:
  LOKI_USERNAME: log-collector
  LOKI_PASSWORD: synthetic-push-token-do-not-use-in-prod
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluent-bit-config
  namespace: logging
data:
  fluent-bit.conf: |
    [SERVICE]
        Flush         1
        Log_Level     info
        Daemon        off
        Parsers_File  parsers.conf
        HTTP_Server   On
        HTTP_Listen   0.0.0.0
        HTTP_Port     2020

    [INPUT]
        Name              tail
        Tag               kube.*
        Path              /var/log/pods/*/*/*.log
        Parser            cri
        DB                /var/log/flb_kube.db
        Mem_Buf_Limit     5MB
        Skip_Long_Lines   On
        Refresh_Interval  10

    [FILTER]
        Name                kubernetes
        Match               kube.*
        Kube_URL            https://kubernetes.default.svc:443
        Kube_CA_File        /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        Kube_Token_File     /var/run/secrets/kubernetes.io/serviceaccount/token
        Merge_Log           On
        Keep_Log            Off

    [OUTPUT]
        Name          loki
        Match         kube.*
        Host          loki-gateway.logging.svc.cluster.local
        Port          3100
        URI           /loki/api/v1/push
        Http_User     ${LOKI_USERNAME}
        Http_Passwd   ${LOKI_PASSWORD}
        Labels        job=fluent-bit, namespace=$kubernetes['namespace_name']
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluent-bit
  namespace: logging
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: fluent-bit
  template:
    metadata:
      labels:
        app.kubernetes.io/name: fluent-bit
    spec:
      serviceAccountName: fluent-bit
      containers:
        - name: fluent-bit
          image: cr.fluentbit.io/fluent/fluent-bit:3.2.0
          env:
            - name: LOKI_USERNAME
              valueFrom:
                secretKeyRef:
                  name: loki-credentials
                  key: LOKI_USERNAME
            - name: LOKI_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: loki-credentials
                  key: LOKI_PASSWORD
          volumeMounts:
            - name: config
              mountPath: /fluent-bit/etc/fluent-bit.conf
              subPath: fluent-bit.conf
            - name: varlog
              mountPath: /var/log
              readOnly: true
      volumes:
        - name: config
          configMap:
            name: fluent-bit-config
        - name: varlog
          hostPath:
            path: /var/log

Predict: results this lesson prints

Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

What result does the lesson show for this command?

$ kind create cluster --config kind-cluster.yaml --name devops-lab
Show the lesson's result

The lesson shows in WSL Hands-On Lab:

Creating cluster "devops-lab" ...
 ✓ Ensuring node image (kindest/node:v1.29.2)
 ✓ Preparing nodes 📦 📦 📦
 ✓ Writing configuration 📜
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Joining worker nodes 🤝
Set kubectl context to "kind-devops-lab"

What result does the lesson show for this command?

$ kubectl get nodes
Show the lesson's result

The lesson shows in WSL Hands-On Lab:

NAME                        STATUS   ROLES           AGE   VERSION
devops-lab-control-plane    Ready    control-plane   2m    v1.29.2
devops-lab-worker           Ready    <none>          90s   v1.29.2
devops-lab-worker2          Ready    <none>          90s   v1.29.2

What result does the lesson show for this command?

$ kubectl top nodes
Show the lesson's result

The lesson shows:

error: Metrics API not available

Practice: troubleshoot and decide

Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

Troubleshooting drill

A pod that never starts

Output recorded from a real run on minikube v1.34.0 (Docker driver), Kubernetes v1.31.0, one node with 2 CPUs; no cloud account needed. Nothing runs on your machine.

Builds on Under-The-Hood Architecture & Networking, Troubleshooting & Disaster Recovery.

A teammate copied a Deployment for the api service from a sizing doc written for a large production node. It requests 16 CPUs per pod. The cluster is a single node with 2 CPUs. They run kubectl apply and the command succeeds.

  1. Step 1 of 3: Predict before you look: what state is the api pod in a few seconds after the apply?

Design decision

Does this team need Kubernetes yet?

Builds on Under-The-Hood Architecture & Networking, Real-World Project: 3-Tier App.

The lesson's project grows from a solo developer on Kind to 20 engineers on EKS to 500+ engineers on multi-cluster GitOps. Your team sits before the middle tier: four developers, one stateless web API, one PostgreSQL database, steady traffic, and nobody whose job is running infrastructure. You are moving off a single hand-built VM.

Constraints

  • Deploys must be repeatable and roll back without someone logging in to the server
  • The API must survive one machine or zone failing
  • No one on the team can spend a large share of their week on cluster operations
  • More services are possible next year but not planned
Which do you choose?

Lab: simulated terminal, nothing runs on your machine

Simulated nothing runs on your machine

  1. 1 Create the cluster (takes ~2 min): Run kind create cluster --config kind-cluster.yaml --name devops-lab
Create the cluster (takes ~2 min): Run kind create cluster --config kind-cluster.yaml --name devops-lab

Ready. Type the command for the current goal.

Check yourself

A Pending Pod has no nodeName yet. How does the scheduler choose its node?

Explanation

In 'Under-The-Hood Architecture & Networking', the scheduler watches Pending Pods, runs Filtering and Scoring, and writes the chosen nodeName through a binding. The kubelet starts containers after assignment.

Which workload resource is designed for databases requiring stable network identities and dedicated persistent storage?

Explanation

In 'Core Components & Objects' (components), StatefulSet is designated for 'Ordered Pod deployment with stable network identity and persistent storage' and recommended for 'databases, Kafka, Elasticsearch.'

A Deployment rollout is stuck and a new Pod's container has restarted. You need the previous container instance's logs. Which command fits?

Explanation

In 'Troubleshooting & Disaster Recovery', 'Deployment stuck in Progressing during rollout' shows 'kubectl logs <new-pod-name> --previous'. The other commands inspect ReplicaSets, watch rollout status, or roll back; they do not retrieve the previous instance's logs.

You are comparing Calico VXLAN with Cilium direct routing. Which mechanism does the lesson associate with Cilium avoiding encapsulation?

Explanation

In 'Under-The-Hood Architecture & Networking', Cilium uses eBPF programs at Linux kernel TC hooks and BPF maps. The lesson associates Felix, UDP 4789 encapsulation, and reduced MTU with the Calico VXLAN discussion.

How does an accepted Deployment object become persisted cluster state?

The API server writes it to etcd, which commits the write when a quorum acknowledges it.

Space flips the current card.

Capability coverage: L1, L2, L3 covered

No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

Skills by experience level for this lesson
SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
Understand Missing · 3 sections Not covered Not covered Not covered
Operate Not covered Missing · 3 sections Not covered Not covered
Troubleshoot Not covered Not covered Missing · 1 section Not covered
Automate Not covered Not covered Not covered Not covered
Secure Not covered Not covered Not covered Not covered
Observe Not covered Not covered Not covered Not covered
Design Not covered Not covered Not covered Not covered
Make trade-offs Not covered Not covered Not covered Not covered

How this lesson fits each role