Kubernetes
Kubernetes continuously reconciles declared workload state with running containers across a cluster.
Overview
Kubernetes runs a control plane that stores declared resources and controllers that reconcile actual cluster state toward them. Pods are the scheduling unit; Deployments manage replaceable replicas and rollout; Services and EndpointSlices provide stable discovery over changing pods; and Gateway or Ingress resources control external routes. Startup, readiness, liveness, requests, limits, disruption budgets, autoscaling, and graceful termination must agree with real application behavior. Configuration, secrets, workload identity, policy, and telemetry stay separate from immutable images so the same artifact can move safely through environments.
What you will learn
- Explain clusters, nodes, Pods, controllers, Services, and configuration resources.
- Deploy a .NET workload with safe rollout and rollback behavior.
- Design startup, readiness, and liveness probes with distinct meanings.
- Set resource requests, limits, disruption protection, and autoscaling deliberately.
- Apply pod security, secret, networking, and identity controls.
- Operate deployments using events, logs, metrics, traces, and declarative change history.
Prerequisites
- Working knowledge of container images and registries.
- Basic YAML, HTTP, DNS, and ASP.NET Core health behavior.
- kubectl and access to a development cluster for deployment exercises.
When to use Kubernetes
Good fit
- Multiple containerized services need consistent scheduling, discovery, rollout, policy, and recovery.
- Teams can operate a platform or use a managed Kubernetes service responsibly.
- Workloads benefit from declarative scaling and portable orchestration APIs.
Choose another approach when
- A small workload is simpler and cheaper on a managed application or container service.
- The team cannot fund cluster security, upgrades, observability, and on-call ownership.
- Using Kubernetes only to copy a virtual-machine deployment model without container readiness.
Key concepts
Controllers watch resources and repeatedly reconcile observed state toward the declared specification.
Pods are scheduling units; Deployments manage replica sets, updates, rollback, and availability.
Services provide stable internal discovery while ingress or gateways expose controlled external routes.
Startup, readiness, liveness, requests, and limits inform safe scheduling and traffic decisions.
ConfigMaps, Secrets, service accounts, and workload identity provide environment data and controlled access without rebuilding images.
Rollout strategy, termination, disruption budgets, replica scaling, and capacity policy keep availability and demand response coordinated.
PersistentVolumes, claims, StatefulSets, operators, and managed services provide different ownership models for data that outlives pods.
Admission policy, RBAC, network controls, events, logs, metrics, and traces make declared workloads governable and diagnosable.
Architecture
External traffic enters a gateway and Service, which selects ready .NET pods managed by a Deployment and connected to managed state.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The Kubernetes Inventory API separates liveness from readiness in application code and ships manifests for a safe Deployment, stable Service, disruption budget, pod security, resources, and horizontal autoscaling.
- 01Define workload ownership
Choose a Deployment for replaceable stateless replicas and use StatefulSet or Job only when their ordering or completion semantics are required.
- 02Label and select consistently
Use stable recommended labels and ensure the Deployment selector and Service selector match the pod template exactly.
- 03Configure the container
Deploy an immutable image, named port, environment-neutral command, external configuration, and explicit security context.
- 04Model lifecycle signals
Use startup for slow initialization, readiness for traffic eligibility, and liveness only for process states a restart can repair.
- 05Budget resources
Set requests from measured steady demand, limits with runtime behavior in mind, and namespace quotas to protect shared capacity.
- 06Make rollout safe
Coordinate readiness, max unavailable, surge, termination grace, pre-stop behavior, and a PodDisruptionBudget.
- 07Expose and scale
Use a Service for stable discovery, Gateway or Ingress for controlled external traffic, and scale on a meaningful constrained signal.
- 08Secure and observe
Apply workload identity, least-privilege RBAC, secret delivery, network policy, admission rules, structured telemetry, and actionable alerts.
Code example
Readiness controls traffic while liveness detects a stuck process; resource requests give the scheduler useful information.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 3
template:
spec:
containers:
- name: api
image: ghcr.io/example/orders-api:1.4.0
ports:
- containerPort: 8080
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
livenessProbe:
httpGet: { path: /health/live, port: 8080 }
resources:
requests: { cpu: 100m, memory: 128Mi }
limits: { memory: 512Mi }Testing strategy
Validate application lifecycle behavior, rendered manifests, and real rollout behavior.
- Unit-test readiness state transitions and cancellation.
- Validate manifests against schemas and organization policy.
- Deploy to an ephemeral namespace and wait for rollout completion.
- Query Service endpoints rather than only port-forwarding a Pod.
- Delete pods and drain a node to observe recovery and disruption behavior.
- Run rollback and configuration failure drills before production.
Security considerations
Cluster defaults are not a complete workload security boundary.
- Run as non-root with seccomp RuntimeDefault, no privilege escalation, and dropped capabilities.
- Use a read-only root filesystem and explicit writable volumes.
- Grant the service account only required API permissions.
- Use workload identity and an external secret provider instead of long-lived credentials.
- Restrict ingress and egress using network policy where the network implementation enforces it.
- Enforce image provenance, approved registries, and pod standards at admission.
Performance and scalability
Scheduling and autoscaling work only when requests and signals represent reality.
- Load-test under configured CPU and memory limits.
- Size requests from observed percentiles rather than guesses.
- Understand .NET GC behavior under container memory limits.
- Scale on latency, queue depth, concurrency, or another demand signal when CPU is insufficient.
- Set stabilization and rate policies to avoid scaling oscillation.
- Protect dependencies from a replica surge.
Deployment and operations
Declarative delivery should make every change observable and reversible.
- Render and review manifests before apply.
- Deploy immutable image digests and record source provenance.
- Wait for rollout status and run a Service-level smoke test.
- Use progressive traffic for high-risk changes.
- Pause or roll back when service-level indicators regress.
- Keep cluster and API-version upgrade compatibility under continuous test.
Common problems and fixes
Pod stays Pending.
Likely cause: No node satisfies resource, affinity, taint, volume, or policy requirements.
Fix: Inspect pod events and compare requests and scheduling constraints with node capacity.
CrashLoopBackOff repeats.
Likely cause: The process exits, configuration is invalid, or liveness kills startup.
Fix: Inspect previous container logs, events, exit code, and startup probe settings.
Pods run but receive no Service traffic.
Likely cause: Labels, selector, target port, or readiness do not match.
Fix: Inspect EndpointSlices, pod labels, named ports, and readiness results.
Rollout stalls at unavailable replicas.
Likely cause: New pods never become ready or capacity cannot satisfy surge requests.
Fix: Describe the rollout and pods, correct readiness or capacity, then resume or roll back.
Healthy pods restart during a database outage.
Likely cause: Liveness incorrectly depends on the database.
Fix: Keep liveness local to process health and place dependency state in readiness with bounded checks.
HPA oscillates or never scales.
Likely cause: Requests or metric targets are missing or unrelated to demand.
Fix: Correct resource requests, inspect metric availability, and add stabilization behavior.
Best practices
- Set realistic resource requests using observed workload data.
- Use separate startup, readiness, and liveness semantics.
- Deploy immutable image tags or digests and record configuration provenance.
- Plan disruption budgets, graceful shutdown, rollout safety, and rollback together.
- Apply least-privilege workload identity, pod security, and network policy.
- Use managed control planes where appropriate and continuously test cluster upgrades.
Production checklist
- Controller and service selectors are correct.
- Immutable image identity and provenance are recorded.
- Startup, readiness, and liveness semantics are distinct.
- Requests, limits, and autoscaling are load-tested.
- Graceful termination and disruption budgets are verified.
- Pod security, RBAC, identity, secrets, and network policy are enforced.
- Rollout, smoke, rollback, and disaster drills are automated.
- Events, logs, metrics, traces, and service objectives are actionable.
Common interview questions
What is the difference between readiness and liveness probes?
Readiness decides whether a pod should receive traffic. Liveness decides whether Kubernetes should restart the container.
What does a Kubernetes Service provide?
It gives a stable virtual address and discovery name over a changing set of selected pods.
Why set resource requests?
The scheduler uses requests to place pods, and autoscaling or capacity decisions depend on having meaningful resource expectations.
What is the difference between a Deployment and StatefulSet?
A Deployment manages interchangeable replicas; a StatefulSet adds stable identity and ordered storage or lifecycle semantics for workloads that truly require them.
Why is a PodDisruptionBudget not a full availability guarantee?
It limits certain voluntary disruptions, but it cannot prevent node failure, application crashes, capacity shortages, or unsafe rollouts.
What happens during Deployment rollout?
The controller creates a new ReplicaSet and scales old and new sets according to surge and unavailable limits while pod readiness determines usable capacity.
When should an application use a startup probe?
Use it when legitimate initialization may exceed the liveness window; it prevents liveness and readiness checks from taking effect until startup succeeds.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Kubernetes Inventory API
A .NET 10 service with safe Deployment, Service, disruption, security, resource, probe, and autoscaling manifests.
- Run
dotnet run --project src/KubernetesInventoryApi- Test
dotnet test KubernetesInventoryApi.slnx