PART 2: ADVANCED CONCEPTS
8. Ingress
An Ingress provides HTTP/HTTPS routing from outside the cluster to Services inside. It's the standard way to expose web applications.
Why Ingress?
Without Ingress, you need a LoadBalancer Service per app (expensive). With Ingress, you have one external IP and route to many Services by hostname/path.
Ingress Requires an Ingress Controller
Kubernetes doesn't ship with an Ingress Controller. You must install one:
| Controller | Notes |
| NGINX Ingress | Most popular, stable |
| Traefik | Modern, easy config |
| HAProxy Ingress | High performance |
| Contour | Envoy-based |
| Istio Gateway | If using Istio |
| AWS Load Balancer Controller | AWS-native (ALB) |
A Basic Ingress
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
Path Types
| Type | Behavior |
| Prefix | Match by URL path prefix |
| Exact | Match exact path only |
| ImplementationSpecific | Depends on controller |
TLS Termination
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: tls-ingress
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: tls-secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
Multiple Hosts
yaml
spec:
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api-service
port:
number: 80
- host: www.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
Common Ingress Annotations (NGINX)
| Annotation | Purpose |
nginx.ingress.kubernetes.io/rewrite-target | Rewrite URL path |
nginx.ingress.kubernetes.io/ssl-redirect | Force HTTPS |
nginx.ingress.kubernetes.io/proxy-body-size | Max upload size |
nginx.ingress.kubernetes.io/rate-limit | Rate limiting |
nginx.ingress.kubernetes.io/auth-type | Basic auth |
cert-manager.io/cluster-issuer | Auto TLS via cert-manager |
The Ingress Evolution: Gateway API
The Gateway API is the successor to Ingress, addressing its limitations:
- Multi-tenancy (Infrastructure vs Application)
- Role separation (ClusterAdmin vs AppDeveloper)
- More expressive routing (header matching, weights)
- Cross-namespace references
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: web-route
spec:
parentRefs:
- name: my-gateway
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: web-service
port: 80
We'll cover Gateway API in depth in Stage 7 (Networking).
9. Namespaces
A Namespace is a logical partition of a cluster. It provides scope for names, RBAC, quotas, and policies.
Why Namespaces?
| Use Case | Benefit |
| Multi-team | Isolate teams |
| Multi-environment | dev, staging, prod in one cluster |
| Resource quotas | Limit total resources per team |
| RBAC | Restrict users to specific namespaces |
| Network policies | Isolate traffic by namespace |
Built-in Namespaces
| Namespace | Purpose |
| default | Where resources go if you don't specify |
| kube-system | Kubernetes components (kube-dns, kube-proxy) |
| kube-public | Public data (rarely used) |
| kube-node-lease | Node heartbeat leases |
Creating and Using Namespaces
bash
# Create
kubectl create namespace dev
# List
kubectl get namespaces
# Set as default for current context
kubectl config set-context --current --namespace=dev
# Use in commands
kubectl get pods -n dev
kubectl get pods --all-namespaces
YAML with Namespace
yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: v1
kind: Pod
metadata:
name: my-pod
namespace: dev
Resource Quotas
ResourceQuota limits total resource consumption per namespace.
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: dev-quota
namespace: dev
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
persistentvolumeclaims: "10"
pods: "50"
services.loadbalancers: "2"
Effect: If a namespace reaches its quota, new resource creation fails.
LimitRange
LimitRange sets default requests/limits for Pods and containers.
yaml
apiVersion: v1
kind: LimitRange
metadata:
name: dev-limits
namespace: dev
spec:
limits:
- default:
cpu: 500m
memory: 512Mi
defaultRequest:
cpu: 100m
memory: 128Mi
type: Container
- max:
cpu: "2"
memory: 2Gi
min:
cpu: 10m
memory: 16Mi
type: Container
What Namespaces Don't Isolate
| Aspect | Isolated? |
| Names | ✅ Yes |
| RBAC | ✅ Yes |
| Resource quotas | ✅ Yes |
| Pods, Services, Deployments | ✅ Yes |
| Nodes | ❌ No (cluster-scoped) |
| PersistentVolumes | ❌ No (cluster-scoped) |
| ClusterRoles | ❌ No (cluster-scoped) |
| CRDs | ❌ No (cluster-scoped) |
| Network | ⚠️ Only with NetworkPolicies |
Important: Namespaces are a logical boundary, not a security boundary by default. You need NetworkPolicies and RBAC to make them secure.
10. Helm
Helm is the package manager for Kubernetes. It packages Kubernetes manifests into reusable Charts with template variables, so you can deploy the same application with different configurations.
Why Helm?
| Without Helm | With Helm |
| Copy-paste YAML for each environment | One chart, many values files |
| Manual versioning | Chart versions + release history |
| Painful rollbacks | helm rollback |
| No dependency management | Charts can depend on charts |
Core Concepts
| Concept | Description |
| Chart | A package (directory) of Kubernetes manifests + templates |
| Release | An instance of a chart deployed to a cluster |
| Values | Configuration variables |
| Repository | A collection of charts |
Chart Structure
text
mychart/
├── Chart.yaml # Metadata
├── values.yaml # Default values
├── templates/ # Kubernetes manifests (templated)
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── _helpers.tpl # Helper templates
│ └── NOTES.txt # Post-install notes
├── charts/ # Subcharts (dependencies)
└── .helmignore # Files to ignore
Chart.yaml
yaml
apiVersion: v2
name: mychart
description: A Helm chart for my app
type: application
version: 1.0.0 # Chart version
appVersion: "1.0.0" # App version
values.yaml
yaml
replicaCount: 3
image:
repository: nginx
tag: "1.25-alpine"
pullPolicy: IfNotPresent
service:
type: ClusterIP
port: 80
ingress:
enabled: false
className: nginx
hosts:
- host: chart-example.local
paths:
- path: /
pathType: Prefix
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
A Templated Manifest
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "mychart.fullname" . }}
labels:
{{- include "mychart.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
{{- include "mychart.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "mychart.selectorLabels" . | nindent 8 }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- containerPort: {{ .Values.service.port }}
resources:
{{- toYaml .Values.resources | nindent 10 }}
Helm Commands
bash
# Create a new chart
helm create mychart
# Template locally (see rendered output)
helm template mychart
# Install
helm install my-release ./mychart
# Install with custom values
helm install my-release ./mychart -f prod-values.yaml
# Install with --set
helm install my-release ./mychart --set replicaCount=5
# List releases
helm list
helm list -A
# Upgrade
helm upgrade my-release ./mychart
# Upgrade or install
helm upgrade --install my-release ./mychart
# Rollback
helm rollback my-release 1
# History
helm history my-release
# Uninstall
helm uninstall my-release
# Repos
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm search repo nginx
# Install from repo
helm install my-nginx bitnami/nginx
Helm Template Functions
| Function | Purpose |
include | Include a template |
tpl | Render a string as template |
toYaml | Convert to YAML |
nindent | Indent + newline |
default | Default value |
quote | Wrap in quotes |
required | Fail if missing |
lookup | Query cluster |
Helm Best Practices
| Practice | Why |
Use helm create as a starting point | Best-practice scaffold |
| One chart per application | Reusable, testable |
| Version charts semantically | 1.0.0, 1.1.0, 2.0.0 |
| Store charts in a repo | Artifact Hub, OCI, ChartMuseum |
Use .helmignore | Don't ship garbage |
Test with helm template before install | Catch errors early |
Use --atomic for installs | Rollback on failure |
| Use Helm Secrets or SOPS for secrets | Don't commit secrets |
Lint with helm lint | Catch issues in CI |
Helm vs Kustomize
| Aspect | Helm | Kustomize |
| Templating | Go templates | Overlays (no templating) |
| Packaging | Charts | Directories |
| Values | values.yaml | Patches |
| Ecosystem | Huge (Artifact Hub) | Native in kubectl |
| Complexity | Higher | Lower |
| Best For | Distributing apps | Configuring base manifests |
Both are valid. Many teams use Helm for third-party charts and Kustomize for their own apps.
11. Labels, Selectors, and Annotations
These three concepts are the glue of Kubernetes.
Labels
Labels are key-value pairs attached to objects for identification and selection.
yaml
metadata:
labels:
app: nginx
environment: production
version: "1.25"
tier: frontend
Rules:
- Keys: 63 chars max, alphanumeric +
-_. - Values: 63 chars max, alphanumeric +
-_. - Max 64 labels per object
Selectors
Selectors choose objects by labels.
Equality-based:
yaml
selector:
matchLabels:
app: nginx
environment: production
Set-based:
yaml
selector:
matchExpressions:
- key: environment
operator: In
values: [production, staging]
- key: tier
operator: NotIn
values: [database]
kubectl with Selectors
bash
# Equality
kubectl get pods -l app=nginx
kubectl get pods -l app=nginx,environment=production
# Set-based
kubectl get pods -l 'environment in (production,staging)'
kubectl get pods -l 'tier notin (database)'
kubectl get pods -l '!version'
Annotations
Annotations are key-value pairs for non-identifying metadata. They can't be used in selectors.
yaml
metadata:
annotations:
description: "Main web server"
maintainer: "[email protected]"
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
deployment.kubernetes.io/revision: "3"
Use cases:
- Configuration for controllers (Ingress controllers, cert-manager)
- Deployment metadata
- Monitoring configuration
- Documentation
Labels vs Annotations
| Aspect | Labels | Annotations |
| Used in selectors | ✅ Yes | ❌ No |
| Size limit | 63 chars | 256 KB total |
| Purpose | Identify and select | Store arbitrary metadata |
| Indexed by K8s | ✅ Yes | ❌ No |
Standard Label Conventions
| Label | Use |
app.kubernetes.io/name | Application name |
app.kubernetes.io/instance | Unique instance ID |
app.kubernetes.io/version | App version |
app.kubernetes.io/component | Component (e.g., web, db) |
app.kubernetes.io/part-of | Parent system |
app.kubernetes.io/managed-by | Tool (helm, kubectl) |
Example:
yaml
metadata:
labels:
app.kubernetes.io/name: nginx
app.kubernetes.io/instance: nginx-prod
app.kubernetes.io/version: "1.25"
app.kubernetes.io/component: web
app.kubernetes.io/part-of: ecommerce
app.kubernetes.io/managed-by: helm
12. Resource Requests and Limits
Resource management is foundational. Getting it wrong causes instability.
Requests vs Limits
| Aspect | Requests | Limits |
| Purpose | Guaranteed minimum | Enforced maximum |
| Scheduling | Used to find nodes | Not used |
| CPU | Guaranteed share | Throttled if exceeded |
| Memory | Guaranteed | OOMKilled if exceeded |
| QoS | Determines class | Determines class |
The Four Cases
| Case | QoS Class | Behavior |
| Requests == Limits | Guaranteed | Highest priority, best isolation |
| Requests < Limits | Burstable | Can burst, may be throttled/killed |
| No requests/limits | BestEffort | Lowest priority, first to die |
Example
yaml
spec:
containers:
- name: app
resources:
requests:
cpu: 100m # 0.1 CPU guaranteed
memory: 128Mi # 128 MiB guaranteed
limits:
cpu: 500m # Up to 0.5 CPU
memory: 256Mi # Up to 256 MiB
CPU Units
| Value | Meaning |
| 1 | 1 full CPU core |
| 500m | 0.5 core (500 millicores) |
| 100m | 0.1 core |
| 1m | 0.001 core |
Memory Units
| Value | Meaning |
| Mi | Mebibyte (1024²) |
| Gi | Gibibyte (1024³) |
| M | Megabyte (1000²) |
| G | Gigabyte (1000³) |
Always use Mi/Gi for consistency.
The Problems
No requests = unpredictable scheduling.
K8s thinks the Pod needs 0 resources. Nodes can be oversubscribed. Pods starve.
No limits = noisy neighbors.
A Pod with a memory leak can consume all node memory and kill other Pods.
Too-low limits = throttling.
Apps get CPU throttled or OOMKilled for no good reason.
Too-high limits = wasted resources.
Nodes have low utilization but can't fit more Pods.
Best Practices
| Rule | Why |
| Always set requests | Predictable scheduling |
| Set limits for memory | Prevent OOM of other Pods |
| Consider removing CPU limits | CPU is compressible; throttling hurts |
| Set requests = limits for critical apps | Guaranteed QoS |
| Start with profiling data | Don't guess |
| Use VPA to recommend values | Data-driven sizing |
| Monitor throttling | container_cpu_cfs_throttled_seconds_total |
QoS Classes in Detail
| QoS | Conditions | Priority | When Node Pressure |
| Guaranteed | requests == limits (CPU and memory) | Highest | Killed last |
| Burstable | requests < limits | Medium | Killed if using > requests |
| BestEffort | No requests/limits | Lowest | Killed first |
Eviction Order
When a node is under memory pressure:
- BestEffort Pods evicted first
- Burstable Pods exceeding requests evicted next
- Guaranteed Pods evicted last
13. StatefulSets and DaemonSets
StatefulSets
StatefulSets manage Pods with stable identities — each Pod has a persistent name, hostname, and storage.
Key differences from Deployments:
| Aspect | Deployment | StatefulSet |
| Pod name | nginx-abc123 (random) | postgres-0, postgres-1 (ordered) |
| Hostname | Random | Stable |
| Storage | Shared or none | Per-Pod PVC |
| Startup order | Parallel | Sequential (0 → 1 → 2) |
| Shutdown order | Parallel | Reverse (2 → 1 → 0) |
| Headless Service | Optional | Required |
Use cases:
- Databases (PostgreSQL, MySQL, MongoDB)
- Message queues (Kafka, RabbitMQ, NATS)
- Distributed caches (Redis Cluster, Elasticsearch)
- Any app needing stable identity + storage
Example:
yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: fast-ssd
resources:
requests:
storage: 100Gi
Each Pod gets its own PVC: data-postgres-0, data-postgres-1, data-postgres-2.
DaemonSets
DaemonSets ensure a Pod runs on every node (or a subset). Used for node-level services.
Use cases:
- Log collectors (Fluent Bit, Filebeat)
- Monitoring agents (Prometheus Node Exporter, Datadog)
- Networking (CNI plugins, kube-proxy)
- Storage (CSI node plugins)
- Security (Falco, Tetragon)
Example:
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-exporter
spec:
selector:
matchLabels:
app: node-exporter
template:
metadata:
labels:
app: node-exporter
spec:
hostNetwork: true
hostPID: true
containers:
- name: node-exporter
image: prom/node-exporter:v1.7.0
ports:
- containerPort: 9100
DaemonSets run on control plane nodes only if they tolerate the control-plane taint.
14. Jobs and CronJobs
Jobs
A Job runs Pods to completion. Unlike Deployments (which run forever), Jobs finish.
Use cases:
- Database migrations
- Batch processing
- One-time setup tasks
Example:
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: myapp:1.0
command: ["python", "manage.py", "migrate"]
Job parameters:
| Parameter | Purpose |
| completions | Number of successful completions |
| parallelism | Max concurrent Pods |
| backoffLimit | Retries before failure |
| activeDeadlineSeconds | Timeout |
CronJobs
A CronJob runs Jobs on a schedule (like cron).
Example:
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup
spec:
schedule: "0 2 * * *" # Every day at 2 AM
concurrencyPolicy: Forbid # Don't run overlapping
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup-tool:1.0
Cron schedule format:
text
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sun=0)
│ │ │ │ │
* * * * *
Concurrency policies:
| Policy | Behavior |
| Allow | Multiple Jobs can run concurrently |
| Forbid | Skip if previous Job still running |
| Replace | Kill previous, start new |
1:1 copy of the class Google Doc, code in code blocks.