Docker, Kubernetes and pod management
Practical, exam-focused notes on Docker (containers, images, Dockerfile, common commands) and Kubernetes (pods, deployments, services, volumes, lifecycle and pod management) with examples and commands to remember.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Containers make application packaging, deployment and resource isolation simple for engineers. Docker provides the tools to build and run containers; Kubernetes automates running containers at scale (scheduling, scaling, updates, service discovery). Engineers use these for development, CI/CD, production deployment and managing microservices.
Key ideas
Docker: a popular platform to build, distribute and run container images. Key components: Dockerfile (build recipe), docker daemon (runs containers), Docker CLI (user commands), registry (image store).
Dockerfile: a text file of instructions (FROM, RUN, COPY, CMD, EXPOSE, ENV) to create an image. Exact semantics: filesystem-changing instructions (e.g., RUN, COPY, ADD) create new filesystem layers; metadata-only instructions (e.g., ENV, EXPOSE, WORKDIR, CMD) update image config but do not add a new filesystem layer. The final image is the ordered stack of filesystem layers plus image metadata.
Kubernetes: an open-source system for automating deployment, scaling and management of containerized applications. Key assumptions: cluster of machines (nodes) managed by a control plane. Draw: one control plane box (API server, scheduler, controller-manager, etcd) connected to multiple node boxes (kubelet, kube-proxy) each running pods. Objects are organized into namespaces to logically isolate resources (most API objects are namespace-scoped; nodes, PVs, etc. are cluster-scoped).
Pod: the smallest deployable unit in Kubernetes; a pod is one or more containers that share the same network namespace (IP address and ports) and optionally shared volumes. Exact definition: containers in a pod share localhost and storage; they are scheduled together on one node. Pods can also define initContainers that run to completion before app containers start. Pod lifecycle phases: Pending, Running, Succeeded, Failed, Unknown.
Node: a worker machine (VM or physical) that runs pods, has a kubelet agent, a container runtime (e.g., containerd/CRI-O) to run containers, and typically kube-proxy (or an eBPF dataplane) for Service networking.
Deployment: a controller that manages a ReplicaSet to maintain a desired number of pod replicas and supports rolling updates and rollbacks. Related workload controllers: StatefulSet (stable network IDs and storage for stateful apps), DaemonSet (one pod per node), Job/CronJob (finite/cron tasks).
Service: an abstract way to expose a set of pods as a network service. Types: ClusterIP (internal), NodePort, LoadBalancer, headless Service (clusterIP: None) for direct pod DNS records, and ExternalName (DNS CNAME to an external name). Services get DNS names via CoreDNS. Uses label selectors to choose pods (selectors are optional for some patterns like headless Services pointing to Endpoints).
ConfigMap and Secret: objects to inject configuration data into pods; Secret is for sensitive data (note: Secret is base64-encoded by default, not encrypted unless additional measures used).
PersistentVolume (PV) and PersistentVolumeClaim (PVC): PV is a cluster storage resource; PVC is a request for storage by a pod. Access modes include ReadWriteOnce/ReadOnlyMany/ReadWriteMany (support depends on the provider). StorageClass defines dynamic provisioning rules.
Probes: livenessProbe detects if a container should be restarted; readinessProbe indicates if a container can receive traffic; startupProbe is used for slow-starting containers to delay liveness checks. Common probe types: HTTP GET, TCP socket, exec, and gRPC.
Labels and selectors: labels are key=value attached to objects; selectors match labels to group objects for services and controllers. Selectors support equality- and set-based expressions (matchLabels, matchExpressions); ensure your selector matches the intended labels exactly.
Networking model: each pod gets its own IP; containers in a pod share the IP. Services get a stable virtual IP (ClusterIP) implemented by kube-proxy using iptables/IPVS; some CNI/eBPF dataplanes (e.g., Cilium) can replace kube-proxy. CNI plugins provide pod-to-pod networking across nodes.
Rolling update: change image or spec in a Deployment; Kubernetes creates new pods while terminating old ones according to strategy parameters (maxUnavailable, maxSurge; defaults are 25% unavailable and 25% surge).
Resource requests and limits: requests influence scheduling (guaranteed CPU/memory request), limits cap resource usage. Without requests, the scheduler may pack pods densely. Pods fall into QoS classes based on requests/limits: Guaranteed, Burstable, BestEffort.
Diagrams to draw for exams:
- Control plane and nodes: draw Control Plane (API Server, Scheduler, Controller Manager, etcd) on left, arrows to Nodes (kubelet, kube-proxy) on right, label Pod instances on nodes.
- Pod network: draw a Pod box with two containers inside, label shared network namespace and a volume mounted.
- Deployment update: sequence diagram showing ReplicaSet A with 3 pods -> new ReplicaSet B gradually increases while A decreases according to maxUnavailable/maxSurge.
Formulas (syntax to remember)
docker build -t <name>:<tag> <path> — build image; <name> image name, <tag> tag (default latest), <path> context (usually .)
docker run --name <cname> -p <hostPort>:<containerPort> -v <hostPath>:<containerPath> -e KEY=VAL <image>:<tag> — run container; --name container name, -p port mapping, -v volume bind, -e environment var.
docker ps — list running containers
docker images — list images
docker rm <container>; docker rmi <image> — remove container/image
kubectl apply -f <file.yaml> — create or update resources from YAML
kubectl get pods — list pods
kubectl describe pod <pod-name> — detailed pod info
kubectl logs <pod-name> [-c container] — fetch logs
kubectl exec -it <pod-name> -- <command> — execute command in container
kubectl scale deployment/<name> --replicas=<n> — scale deployment replicas
kubectl set image deployment/<name> <container>=<image>:<tag> — update image (triggers rolling update)
kubectl port-forward <pod|svc>/<name> <localPort>:<remotePort> — forward ports for debugging
YAML fields to remember: apiVersion, kind, metadata: {name, labels}, spec: {containers: [{name, image, ports, env, resources, volumeMounts, readinessProbe, livenessProbe, command, args, imagePullPolicy}], initContainers, restartPolicy, selector (for controllers), volumes}
Worked examples
Example 1 — Build and run a web app in Docker
- Dockerfile (write this file): FROM python:3.9-slim WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 5000 CMD ["python", "app.py"]
- Build:
docker build -t myweb:1.0 . - Run with port mapping and host volume:
docker run --name web -p 8080:5000 -v $(pwd)/data:/app/data myweb:1.0Steps explained: build creates image layers; run maps host port 8080 to container 5000 so browser hits http://localhost:8080; volume mounts persistent host folder. Final check: curl http://localhost:8080 should return app response.
Example 2 — Deploy to Kubernetes with scaling and rolling update
- Deployment YAML (app-deploy.yaml): apiVersion: apps/v1 kind: Deployment metadata: name: web-deploy spec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web image: myweb:1.0 ports: - containerPort: 5000
- Apply:
kubectl apply -f app-deploy.yaml(ensure the image is reachable by the cluster nodes: push to a registry the cluster can pull from, or use tooling like kind load docker-image / minikube image load for local clusters). - Check pods:
kubectl get pods -l app=web— expect 3 pods in Running state. - Scale:
kubectl scale deployment/web-deploy --replicas=5— expect 2 new pods created. - Rolling update (new image):
kubectl set image deployment/web-deploy web=myweb:1.1Kubernetes creates new ReplicaSet with myweb:1.1 and slowly replaces pods (respecting maxUnavailable/maxSurge). Usekubectl rollout status deployment/web-deployto watch.
Example 3 — Readiness and liveness probe trace YAML snippet for container: livenessProbe: httpGet: path: /healthz port: 5000 initialDelaySeconds: 10 periodSeconds: 5 readinessProbe: httpGet: path: /ready port: 5000 initialDelaySeconds: 5 periodSeconds: 3 Trace: Pod starts -> after initialDelaySeconds the readiness probe checks /ready; until it succeeds (successThreshold), the pod remains NotReady (Services won't route traffic to it). If the liveness probe fails failureThreshold consecutive times, the kubelet restarts the container. This prevents sending traffic to not-ready instances and self-heals unhealthy containers.
Common mistakes
- Wrong label selectors: mismatched labels cause Service to select zero pods.
- Storing secrets as plain text ConfigMaps; Secret is only base64 by default — not encrypted at rest unless configured.
- Forgetting resource requests so scheduler packs nodes dangerously; or forgetting limits leading to noisy neighbors.
- Using hostPath volumes carelessly (can break portability and security).
- Expecting Service ClusterIP to be reachable outside cluster without NodePort or LoadBalancer or ingress.
For your exam
Question types you will see: definitions (pod, image, registry), short notes (pod lifecycle, volumes, probe types), diagram questions (draw Kubernetes control plane and node), YAML writing (simple Deployment or Service), command questions (kubectl/docker syntax), short programs (Dockerfile), and scenario-based (how to design rolling updates, storage for stateful app). What full-marks answers include:
- Clear definition with bold term and its role.
- Assumptions (e.g., Linux kernel, container runtime in place).
- A correct diagram labeled with components and interactions when asked.
- For YAML/program answers: syntactically correct minimal example and explanation of fields used.
- For commands: exact syntax and short explanation of each option.
Quick check
- What is a Pod in Kubernetes?
- Which command builds a Docker image from a Dockerfile in the current directory?
- Name three types of Kubernetes Services and when you use each.
Answers: 1) A Pod is the smallest deployable unit — one or more containers sharing network and storage on the same node. 2)
docker build -t <name>:<tag> .3) ClusterIP for internal-only services; NodePort to expose a port on each node; LoadBalancer to request a cloud load balancer (use in cloud providers).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?