Stage 1, Part 2 of 9, Kubernetes Fundamentals (Day 0/1)

Text

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:

ControllerNotes
NGINX IngressMost popular, stable
TraefikModern, easy config
HAProxy IngressHigh performance
ContourEnvoy-based
Istio GatewayIf using Istio
AWS Load Balancer ControllerAWS-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

TypeBehavior
PrefixMatch by URL path prefix
ExactMatch exact path only
ImplementationSpecificDepends 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)

AnnotationPurpose
nginx.ingress.kubernetes.io/rewrite-targetRewrite URL path
nginx.ingress.kubernetes.io/ssl-redirectForce HTTPS
nginx.ingress.kubernetes.io/proxy-body-sizeMax upload size
nginx.ingress.kubernetes.io/rate-limitRate limiting
nginx.ingress.kubernetes.io/auth-typeBasic auth
cert-manager.io/cluster-issuerAuto TLS via cert-manager

The Ingress Evolution: Gateway API

The Gateway API is the successor to Ingress, addressing its limitations:

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 CaseBenefit
Multi-teamIsolate teams
Multi-environmentdev, staging, prod in one cluster
Resource quotasLimit total resources per team
RBACRestrict users to specific namespaces
Network policiesIsolate traffic by namespace

Built-in Namespaces

NamespacePurpose
defaultWhere resources go if you don't specify
kube-systemKubernetes components (kube-dns, kube-proxy)
kube-publicPublic data (rarely used)
kube-node-leaseNode 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

AspectIsolated?
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 HelmWith Helm
Copy-paste YAML for each environmentOne chart, many values files
Manual versioningChart versions + release history
Painful rollbackshelm rollback
No dependency managementCharts can depend on charts

Core Concepts

ConceptDescription
ChartA package (directory) of Kubernetes manifests + templates
ReleaseAn instance of a chart deployed to a cluster
ValuesConfiguration variables
RepositoryA 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

FunctionPurpose
includeInclude a template
tplRender a string as template
toYamlConvert to YAML
nindentIndent + newline
defaultDefault value
quoteWrap in quotes
requiredFail if missing
lookupQuery cluster

Helm Best Practices

PracticeWhy
Use helm create as a starting pointBest-practice scaffold
One chart per applicationReusable, testable
Version charts semantically1.0.0, 1.1.0, 2.0.0
Store charts in a repoArtifact Hub, OCI, ChartMuseum
Use .helmignoreDon't ship garbage
Test with helm template before installCatch errors early
Use --atomic for installsRollback on failure
Use Helm Secrets or SOPS for secretsDon't commit secrets
Lint with helm lintCatch issues in CI

Helm vs Kustomize

AspectHelmKustomize
TemplatingGo templatesOverlays (no templating)
PackagingChartsDirectories
Valuesvalues.yamlPatches
EcosystemHuge (Artifact Hub)Native in kubectl
ComplexityHigherLower
Best ForDistributing appsConfiguring 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:

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:

Labels vs Annotations

AspectLabelsAnnotations
Used in selectors✅ Yes❌ No
Size limit63 chars256 KB total
PurposeIdentify and selectStore arbitrary metadata
Indexed by K8s✅ Yes❌ No

Standard Label Conventions

LabelUse
app.kubernetes.io/nameApplication name
app.kubernetes.io/instanceUnique instance ID
app.kubernetes.io/versionApp version
app.kubernetes.io/componentComponent (e.g., web, db)
app.kubernetes.io/part-ofParent system
app.kubernetes.io/managed-byTool (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

AspectRequestsLimits
PurposeGuaranteed minimumEnforced maximum
SchedulingUsed to find nodesNot used
CPUGuaranteed shareThrottled if exceeded
MemoryGuaranteedOOMKilled if exceeded
QoSDetermines classDetermines class

The Four Cases

CaseQoS ClassBehavior
Requests == LimitsGuaranteedHighest priority, best isolation
Requests < LimitsBurstableCan burst, may be throttled/killed
No requests/limitsBestEffortLowest 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

ValueMeaning
11 full CPU core
500m0.5 core (500 millicores)
100m0.1 core
1m0.001 core

Memory Units

ValueMeaning
MiMebibyte (1024²)
GiGibibyte (1024³)
MMegabyte (1000²)
GGigabyte (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

RuleWhy
Always set requestsPredictable scheduling
Set limits for memoryPrevent OOM of other Pods
Consider removing CPU limitsCPU is compressible; throttling hurts
Set requests = limits for critical appsGuaranteed QoS
Start with profiling dataDon't guess
Use VPA to recommend valuesData-driven sizing
Monitor throttlingcontainer_cpu_cfs_throttled_seconds_total

QoS Classes in Detail

QoSConditionsPriorityWhen Node Pressure
Guaranteedrequests == limits (CPU and memory)HighestKilled last
Burstablerequests < limitsMediumKilled if using > requests
BestEffortNo requests/limitsLowestKilled first

Eviction Order

When a node is under memory pressure:

  1. BestEffort Pods evicted first
  2. Burstable Pods exceeding requests evicted next
  3. 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:

AspectDeploymentStatefulSet
Pod namenginx-abc123 (random)postgres-0, postgres-1 (ordered)
HostnameRandomStable
StorageShared or nonePer-Pod PVC
Startup orderParallelSequential (0 → 1 → 2)
Shutdown orderParallelReverse (2 → 1 → 0)
Headless ServiceOptionalRequired

Use cases:

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:

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:

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:

ParameterPurpose
completionsNumber of successful completions
parallelismMax concurrent Pods
backoffLimitRetries before failure
activeDeadlineSecondsTimeout

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:

PolicyBehavior
AllowMultiple Jobs can run concurrently
ForbidSkip if previous Job still running
ReplaceKill previous, start new

1:1 copy of the class Google Doc, code in code blocks.