MFormations
Modern DevOps Engineering

Chapitre 3

03 — Kubernetes

03 — Kubernetes

Course: Kubernetes

1. Architecture

1.1 Control Plane Components

┌─────────────────────────────────────┐
│        Control Plane                │
│  ┌──────┐ ┌────────┐ ┌───────────┐ │
│  │ etcd │ │  API   │ │ Scheduler │ │
│  │      │ │ Server │ │           │ │
│  └──────┘ └────────┘ └───────────┘ │
│  ┌───────────────────────────────┐  │
│  │   Controller Manager          │  │
│  │ (Deployment, Node, Namespace…)│  │
│  └───────────────────────────────┘  │
└─────────────────────────────────────┘
         │
    ┌────┴────┐
    │  Node   │
    │ ┌──────┐│
    │ │Kubelet││
    │ ├──────┤│
    │ │Kube-  ││
    │ │Proxy  ││
    │ ├──────┤│
    │ │ Pods  ││
    │ └──────┘│
    └─────────┘

etcd

  • Distributed key-value store
  • Stores all cluster state
  • RAFT consensus algorithm
  • Backup critical — etcdctl snapshot save

kube-apiserver

  • Front-end to the control plane
  • Validates and processes all REST requests
  • Authentication, authorization, admission control
  • kubectl communicates with apiserver

Scheduler

  • Watches for unscheduled Pods
  • Makes binding decisions based on resource requirements, constraints, affinity/anti-affinity
  • Pluggable scheduling policies

Controller Manager

  • Runs controller processes:
    • Node Controller: node health monitoring
    • Replication Controller: maintains correct Pod count
    • Endpoint Controller: populates Service endpoints
    • ServiceAccount & Token Controllers

1.2 Node Components

kubelet

  • Primary node agent
  • Registers node with cluster
  • Ensures Pods are running and healthy
  • Reports node and Pod status

kube-proxy

  • Network proxy per node
  • Maintains network rules (iptables/IPVS)
  • Implements Service abstraction

Container Runtime

  • Runs containers (containerd, CRI-O)
  • Implements CRI (Container Runtime Interface)

2. Core Workloads

2.1 Pods

Smallest deployable unit — one or more containers sharing network and storage.

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.25-alpine
    ports:
    - containerPort: 80
    resources:
      requests:
        cpu: 100m
        memory: 128Mi
      limits:
        cpu: 200m
        memory: 256Mi

2.2 Deployments

Declarative updates for Pods and ReplicaSets.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: app
        image: myapp:1.2.3
        ports:
        - containerPort: 8080
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 3

2.3 StatefulSets

For stateful applications requiring stable network identity and persistent storage.

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
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 10Gi

2.4 DaemonSets

Runs one Pod per node (e.g., logging, monitoring, networking).

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluentd
spec:
  selector:
    matchLabels:
      name: fluentd
  template:
    metadata:
      labels:
        name: fluentd
    spec:
      containers:
      - name: fluentd
        image: fluent/fluentd:v1.16
        volumeMounts:
        - name: varlog
          mountPath: /var/log
      volumes:
      - name: varlog
        hostPath:
          path: /var/log

2.5 Jobs & CronJobs

apiVersion: batch/v1
kind: CronJob
metadata:
  name: backup
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: mybackup:latest
          restartPolicy: OnFailure

3. Services

3.1 Service Types

# ClusterIP (default) — internal cluster access
apiVersion: v1
kind: Service
metadata:
  name: webapp-svc
spec:
  selector:
    app: webapp
  ports:
  - port: 80
    targetPort: 8080
---
# NodePort — external access via node IP:port
apiVersion: v1
kind: Service
metadata:
  name: webapp-nodeport
spec:
  type: NodePort
  selector:
    app: webapp
  ports:
  - port: 80
    targetPort: 8080
    nodePort: 30080
---
# LoadBalancer — cloud LB integration
apiVersion: v1
kind: Service
metadata:
  name: webapp-lb
spec:
  type: LoadBalancer
  selector:
    app: webapp
  ports:
  - port: 80
    targetPort: 8080
---
# Headless — for StatefulSets
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  clusterIP: None
  selector:
    app: postgres

4. Ingress

4.1 Ingress Controller (nginx-ingress)

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - app.example.com
    secretName: app-tls
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: api-svc
            port:
              number: 8080
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend-svc
            port:
              number: 80

5. Configuration & Secrets

5.1 ConfigMaps

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  app.properties: |
    log.level=INFO
    max.connections=100
  NODE_ENV: production

5.2 Secrets

apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
type: Opaque
stringData:
  DB_PASSWORD: "s3cr3t!"
  API_KEY: "sk-xxxx"

6. Persistent Storage

6.1 CSI Drivers

Kubernetes uses the Container Storage Interface (CSI) for storage:

  • AWS EBS CSI, EFS CSI
  • GCP PD CSI, Filestore CSI
  • Azure Disk CSI, Azure File CSI
  • Rook/Ceph, Longhorn, Portworx

6.2 Storage Classes and PVCs

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: fast-ssd
provisioner: kubernetes.io/aws-ebs
parameters:
  type: gp3
  fsType: ext4
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-pvc
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: fast-ssd
  resources:
    requests:
      storage: 50Gi

7. RBAC

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "watch", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: default
subjects:
- kind: User
  name: alice
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

8. Network Policies

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    - namespaceSelector:
        matchLabels:
          name: monitoring
    ports:
    - port: 8080

9. Autoscaling

9.1 Horizontal Pod Autoscaler (HPA)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: webapp-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: webapp
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

9.2 Vertical Pod Autoscaler (VPA)

Recommends CPU/memory requests based on historical usage:

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: webapp-vpa
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: webapp
  updatePolicy:
    updateMode: Auto

10. Pod Security Standards

Three predefined policies: Privileged, Baseline, Restricted.

apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted

11. Helm

11.1 Chart Structure

mychart/
├── Chart.yaml          # Metadata
├── values.yaml         # Default values
├── charts/             # Subcharts
└── templates/
    ├── deployment.yaml
    ├── service.yaml
    ├── ingress.yaml
    └── _helpers.tpl

11.2 Helm Commands

helm create mychart
helm install myapp ./mychart
helm upgrade --install myapp ./mychart --set image.tag=1.2.3
helm rollback myapp 1
helm list
helm get values myapp
helm template ./mychart  # Render locally

12. Custom Resources & Operators

12.1 Custom Resource Definition (CRD)

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: databases.example.com
spec:
  group: example.com
  scope: Namespaced
  names:
    plural: databases
    singular: database
    kind: Database
  versions:
  - name: v1
    served: true
    storage: true
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              engine:
                type: string
              version:
                type: string

12.2 Operators

Operators extend Kubernetes with domain-specific knowledge:

  • Prometheus Operator: Manages Prometheus instances
  • cert-manager: Issues and rotates TLS certificates
  • Crossplane: Infrastructure provisioning from K8s
  • Strimzi: Apache Kafka on Kubernetes
  • Elastic Operator: Elasticsearch on Kubernetes

Summary

Kubernetes provides a powerful platform for deploying, scaling, and managing containerized applications. Mastering its architecture (etcd, apiserver, scheduler, controller-manager, kubelet, kube-proxy), core resources (Pods, Deployments, Services, Ingress), security (RBAC, Network Policies, PSS), and ecosystem (Helm, Operators, CRDs) is essential for modern DevOps engineering.