Table of Contents

    Kubernetes Orchestration

    Model Deployment

    Kubernetes Orchestration

    Deploy and operate a containerized Machine Learning API using Kubernetes Deployments, Pods, Services, ConfigMaps, Secrets, startup and health probes, resource controls, autoscaling, rolling updates, rollback, observability, security policies, and production-readiness practices.

    Introduction

    Docker packages a Machine Learning API into a portable container image. Kubernetes operates that image across one or more machines. It schedules containers, maintains the desired number of replicas, replaces failed instances, provides stable service discovery, controls configuration, and coordinates application updates.

    In this lesson, the FastAPI customer-churn service from the previous lessons is deployed to Kubernetes. The workload uses an immutable container image containing the API and approved model pipeline. Kubernetes manages multiple application Pods behind a stable Service.

    Kubernetes can improve availability and operational consistency, but it does not validate the Machine Learning model. Model quality, input correctness, drift, responsible use, security, and business outcomes still require separate controls.

    Lesson goal: Deploy a versioned ML inference container through Kubernetes and operate it with controlled configuration, health checks, resources, scaling, updates, monitoring, and rollback.

    Learning Objectives

    By the End of This Lesson

    • Explain container orchestration
    • Describe the Kubernetes control plane and worker nodes
    • Distinguish clusters, nodes, Pods, Deployments, and Services
    • Create a Namespace for an ML workload
    • Deploy an immutable ML API image
    • Configure replicas and rolling updates
    • Expose the API through a Kubernetes Service
    • Use ConfigMaps for non-sensitive configuration
    • Use Secrets through controlled mechanisms
    • Configure startup, readiness, and liveness probes
    • Set CPU and memory requests and limits
    • Configure horizontal Pod autoscaling
    • Understand Pod disruption controls
    • Perform rolling updates and rollback
    • Inspect workloads with kubectl
    • Troubleshoot failed Pods and deployments
    • Collect logs, metrics, and traces
    • Apply Kubernetes security controls
    • Connect Kubernetes monitoring to ML observability
    • Create a Kubernetes deployment-readiness checklist

    Prerequisites

    Recommended Knowledge

    • Docker images and containers
    • Container registries
    • FastAPI or Flask deployment
    • Saving and loading ML models
    • YAML fundamentals
    • Command-line usage
    • HTTP endpoints and status codes
    • CPU and memory fundamentals
    • Basic networking and DNS
    • Cloud identity and access control

    Required Tools

    • Docker or an approved compatible container runtime
    • kubectl
    • A local or managed Kubernetes cluster
    • An approved container registry
    • The versioned ML API image
    docker version
    kubectl version --client
    kubectl config current-context
    Safety requirement: Verify the active Kubernetes context and Namespace before applying, changing, or deleting resources.

    What Is Kubernetes?

    Kubernetes is a container-orchestration platform. Users declare the desired state of workloads through Kubernetes resources, and controllers continually work to move the actual cluster state toward that desired state.

    Reconciliation
    Desired State → Kubernetes Controllers → Observed State → Corrective Action
    Capability Purpose
    Scheduling Selects suitable nodes for Pods
    Self-Healing Replaces failed or unavailable workload instances
    Service Discovery Provides stable names for changing Pods
    Load Distribution Routes Service traffic to eligible Pods
    Scaling Changes workload capacity manually or automatically
    Configuration Separates environment configuration from images
    Rollout Coordinates controlled application updates
    Rollback Restores an earlier Deployment revision

    Kubernetes Architecture

    Control Plane

    • Exposes the Kubernetes API
    • Stores cluster state
    • Schedules Pods
    • Runs reconciliation controllers

    Worker Nodes

    • Run application Pods
    • Use a container runtime
    • Report workload status
    • Provide compute, memory, and networking
    Component Responsibility
    API Server Receives and validates Kubernetes API requests
    State Store Preserves cluster configuration and state
    Scheduler Assigns unscheduled Pods to suitable nodes
    Controller Manager Runs control loops for Kubernetes resources
    Node Agent Ensures assigned Pod containers are running
    Container Runtime Runs containers on worker nodes
    Network Proxy Supports Service networking on nodes

    Core Kubernetes Resources

    Resource ML Deployment Purpose
    Namespace Provides a logical scope for related resources
    Pod Runs one or more tightly related containers
    ReplicaSet Maintains a specified number of matching Pods
    Deployment Manages stateless Pods, updates, and revisions
    Service Provides stable network access to matching Pods
    ConfigMap Stores non-sensitive configuration
    Secret Represents sensitive configuration requiring protection
    HorizontalPodAutoscaler Adjusts replica count according to observed metrics
    Job Runs a finite task to completion
    CronJob Runs Jobs according to a schedule
    Ingress Defines supported external HTTP routing through an Ingress controller
    PersistentVolumeClaim Requests persistent storage when a workload requires it

    Pod, ReplicaSet, and Deployment

    Workload Relationship
    Deployment → ReplicaSet → Pods → ML API Containers

    A Pod is an execution unit and may be replaced at any time. A Deployment manages ReplicaSets, while a ReplicaSet maintains the desired number of matching Pods.

    Operational rule: Do not treat an individual Pod name or IP address as a permanent application endpoint. Use a Service for stable access.

    Create a Namespace

    apiVersion: v1
    kind: Namespace
    metadata:
      name: ml-inference
      labels:
        app.kubernetes.io/part-of: machine-learning
        environment: development
    kubectl apply \
      --filename namespace.yaml
    kubectl get namespaces
    Namespace limitation: A Namespace provides logical scope. It does not replace identity, authorization, network policy, resource quotas, or workload security.

    Use Consistent Labels

    labels:
      app.kubernetes.io/name: customer-churn-api
      app.kubernetes.io/instance: customer-churn-api-production
      app.kubernetes.io/version: "1.0.0"
      app.kubernetes.io/component: inference-api
      app.kubernetes.io/part-of: machine-learning
      app.kubernetes.io/managed-by: kubectl

    Labels support selection, grouping, policy, monitoring, and operational reporting. Service and Deployment selectors must match the intended Pods exactly.

    Create a ConfigMap

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: customer-churn-api-config
      namespace: ml-inference
    data:
      MODEL_PATH: /app/artifacts/customer_churn_pipeline.joblib
      METADATA_PATH: /app/artifacts/model_metadata.json
      MAXIMUM_BATCH_SIZE: "100"
      LOG_LEVEL: INFO
    kubectl apply \
      --filename configmap.yaml
    Configuration rule: Use ConfigMaps only for non-sensitive values. Updating a ConfigMap does not automatically guarantee that an existing application process reloads the value.

    Handle Sensitive Configuration

    apiVersion: v1
    kind: Secret
    metadata:
      name: customer-churn-api-secret
      namespace: ml-inference
    type: Opaque
    stringData:
      API_KEY: replace-through-approved-secret-process
    Unsafe Practice Commit a Kubernetes Secret manifest containing production credentials to source control.
    Required Practice Create or synchronize sensitive values through an approved secret system, restrict access, rotate credentials, and audit their use.
    Encoding warning: Base64 representation is encoding, not encryption.

    Create the ML API Deployment

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: customer-churn-api
      namespace: ml-inference
      labels:
        app.kubernetes.io/name: customer-churn-api
        app.kubernetes.io/component: inference-api
    spec:
      replicas: 2
    
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxUnavailable: 0
          maxSurge: 1
    
      selector:
        matchLabels:
          app.kubernetes.io/name: customer-churn-api
    
      template:
        metadata:
          labels:
            app.kubernetes.io/name: customer-churn-api
            app.kubernetes.io/component: inference-api
            app.kubernetes.io/version: "1.0.0"
    
        spec:
          serviceAccountName: customer-churn-api
    
          securityContext:
            runAsNonRoot: true
            seccompProfile:
              type: RuntimeDefault
    
          containers:
            - name: ml-api
              image: registry.example.com/ml/customer-churn-api:1.0.0
              imagePullPolicy: IfNotPresent
    
              ports:
                - name: http
                  containerPort: 8000
                  protocol: TCP
    
              envFrom:
                - configMapRef:
                    name: customer-churn-api-config
    
              env:
                - name: API_KEY
                  valueFrom:
                    secretKeyRef:
                      name: customer-churn-api-secret
                      key: API_KEY
    
              resources:
                requests:
                  cpu: "250m"
                  memory: "512Mi"
                limits:
                  cpu: "1"
                  memory: "1Gi"
    
              startupProbe:
                httpGet:
                  path: /health
                  port: http
                periodSeconds: 5
                failureThreshold: 30
    
              readinessProbe:
                httpGet:
                  path: /ready
                  port: http
                periodSeconds: 10
                timeoutSeconds: 3
                failureThreshold: 3
    
              livenessProbe:
                httpGet:
                  path: /health
                  port: http
                periodSeconds: 20
                timeoutSeconds: 3
                failureThreshold: 3
    
              securityContext:
                allowPrivilegeEscalation: false
                readOnlyRootFilesystem: true
                capabilities:
                  drop:
                    - ALL
    
              volumeMounts:
                - name: temporary-files
                  mountPath: /tmp
    
          volumes:
            - name: temporary-files
              emptyDir: {}
    Example values: Replica count, resources, image location, probe timing, and security settings are starting examples. Validate them against the actual ML model, cluster policy, load tests, and hosting environment.

    Resource Requests and Limits

    Setting Purpose
    CPU Request Represents CPU used by scheduling and resource-based scaling calculations
    Memory Request Represents memory considered during scheduling
    CPU Limit Restricts container CPU consumption according to runtime enforcement
    Memory Limit Sets an upper memory boundary whose breach can terminate the container

    Measure Before Finalizing

    • Model artifact size
    • Memory after model loading
    • Peak inference memory
    • CPU per prediction
    • Request concurrency
    • Startup duration
    • Batch-size effect
    • Latency under load
    • Behavior under resource pressure

    Startup, Readiness, and Liveness Probes

    Probe Question Answered Failure Effect
    Startup Has the slow-starting application initialized? Protects startup from premature liveness failures
    Readiness Can this Pod safely accept requests? Removes the Pod from eligible Service endpoints
    Liveness Should the container be restarted? Triggers container restart after configured failures
    Weak Probe Design Use only a process-level response to indicate that the model is ready for inference.
    Better Probe Design Let readiness verify that the approved artifact, metadata, and required inference resources have initialized successfully.

    Create a Service

    apiVersion: v1
    kind: Service
    metadata:
      name: customer-churn-api
      namespace: ml-inference
      labels:
        app.kubernetes.io/name: customer-churn-api
    spec:
      type: ClusterIP
    
      selector:
        app.kubernetes.io/name: customer-churn-api
    
      ports:
        - name: http
          protocol: TCP
          port: 80
          targetPort: http
    kubectl apply \
      --filename deployment.yaml \
      --filename service.yaml
    Service behavior: The ClusterIP Service provides an internal stable name and routes requests to matching ready Pods.

    Kubernetes Service Types

    Type General Use
    ClusterIP Internal cluster access
    NodePort Exposes a port through cluster nodes
    LoadBalancer Requests external load-balancer integration where supported
    ExternalName Maps a Service name to an external DNS name
    Exposure principle: Keep the prediction API internal unless approved external access is required. Public exposure requires authentication, authorization, transport protection, gateway controls, rate limits, and monitoring.

    Local Port Forwarding

    kubectl port-forward \
      --namespace ml-inference \
      service/customer-churn-api \
      8000:80
    curl http://127.0.0.1:8000/health
    curl http://127.0.0.1:8000/ready
    Development use: Port forwarding is useful for authorized testing and diagnostics. It is not the production exposure architecture.

    Test the Kubernetes Prediction API

    curl \
      --request POST \
      --header "Content-Type: application/json" \
      --data '{
        "tenure_months": 18,
        "monthly_charges": 64.5,
        "total_charges": 1161.0,
        "contract_type": "Monthly",
        "payment_method": "Electronic",
        "tech_support": "No"
      }' \
      http://127.0.0.1:8000/predictions
    Synthetic-input notice: These values are invented for contract testing and do not represent a real customer.

    Inspect Kubernetes Resources

    kubectl get all \
      --namespace ml-inference
    kubectl get pods \
      --namespace ml-inference \
      --output wide
    kubectl describe deployment \
      customer-churn-api \
      --namespace ml-inference
    kubectl get endpoints \
      customer-churn-api \
      --namespace ml-inference

    Inspect For

    • Desired and available replicas
    • Pod readiness
    • Container restart counts
    • Image version
    • Scheduling events
    • Probe failures
    • Resource failures
    • Service selectors
    • Eligible endpoints

    View Application Logs

    kubectl logs \
      --namespace ml-inference \
      deployment/customer-churn-api
    kubectl logs \
      --namespace ml-inference \
      deployment/customer-churn-api \
      --follow \
      --tail=100
    kubectl logs \
      --namespace ml-inference \
      pod/replace-with-pod-name \
      --previous
    Privacy rule: Logs should contain approved operational metadata, not complete prediction payloads, credentials, access tokens, or unnecessary personal information.

    Scale the Deployment Manually

    kubectl scale deployment \
      customer-churn-api \
      --namespace ml-inference \
      --replicas=3
    kubectl get pods \
      --namespace ml-inference \
      --watch
    Scaling limitation: More replicas increase potential capacity only when nodes, networking, dependencies, and downstream systems can support them.

    Configure Horizontal Pod Autoscaling

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: customer-churn-api
      namespace: ml-inference
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: customer-churn-api
    
      minReplicas: 2
      maxReplicas: 10
    
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
            - type: Percent
              value: 100
              periodSeconds: 60
    
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
            - type: Percent
              value: 25
              periodSeconds: 60
    
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: Utilization
              averageUtilization: 60
    kubectl apply \
      --filename hpa.yaml
    kubectl get hpa \
      --namespace ml-inference
    Autoscaling requirement: Resource-based autoscaling depends on meaningful resource requests and an available metrics pipeline. Validate the policy with representative load rather than copying example values directly.

    Choose Useful Scaling Signals

    Signal Possible Use Limitation
    CPU Utilization Useful for CPU-bound model inference May not reflect waiting, queueing, or accelerator load
    Memory Useful when model replicas have variable memory demand Adding Pods may not resolve per-Pod memory limits
    Request Rate Can align capacity with incoming traffic Requires an appropriate metrics adapter
    Queue Length Useful for asynchronous inference workers Requires queue and external-metrics integration
    Inference Latency Can identify load-related response degradation May be affected by downstream systems
    GPU Utilization Useful for accelerator-based inference Requires compatible device and metrics support

    Perform a Rolling Update

    kubectl set image deployment/customer-churn-api \
      ml-api=registry.example.com/ml/customer-churn-api:1.1.0 \
      --namespace ml-inference
    kubectl rollout status \
      deployment/customer-churn-api \
      --namespace ml-inference
    kubectl rollout history \
      deployment/customer-churn-api \
      --namespace ml-inference
    Release rule: Update to an immutable, tested image that identifies the approved application and model versions.

    Roll Back a Deployment

    kubectl rollout undo \
      deployment/customer-churn-api \
      --namespace ml-inference
    kubectl rollout status \
      deployment/customer-churn-api \
      --namespace ml-inference

    Possible Rollback Triggers

    • Readiness failures
    • Elevated request errors
    • Unacceptable latency
    • Memory instability
    • Contract incompatibility
    • Incorrect prediction behavior
    • Security incident
    • Harmful or unequal outcomes
    Rollback limitation: Deployment rollback restores a workload revision. External schema, data, policy, feature, or dependency changes may require additional recovery actions.

    Add a Pod Disruption Budget

    apiVersion: policy/v1
    kind: PodDisruptionBudget
    metadata:
      name: customer-churn-api
      namespace: ml-inference
    spec:
      minAvailable: 1
    
      selector:
        matchLabels:
          app.kubernetes.io/name: customer-churn-api
    Disruption principle: A PodDisruptionBudget helps control voluntary disruptions. It does not guarantee availability during node failure, application failure, insufficient capacity, or dependency outage.

    Spread Replicas Across Nodes

    spec:
      template:
        spec:
          topologySpreadConstraints:
            - maxSkew: 1
              topologyKey: kubernetes.io/hostname
              whenUnsatisfiable: ScheduleAnyway
              labelSelector:
                matchLabels:
                  app.kubernetes.io/name: customer-churn-api

    Topology-spread constraints can reduce concentration of replicas on one node. Scheduling behavior must be evaluated against available nodes, zones, labels, capacity, and availability requirements.

    Schedule Accelerator Workloads

    resources:
      requests:
        cpu: "1"
        memory: "4Gi"
        nvidia.com/gpu: "1"
      limits:
        cpu: "2"
        memory: "8Gi"
        nvidia.com/gpu: "1"
    Accelerator requirement: GPU scheduling requires compatible cluster nodes, drivers, device support, container libraries, quotas, and a workload that demonstrates sufficient benefit.

    Model Artifact Distribution

    Approach Advantages Considerations
    Model Inside Image Application and model form one immutable release Every model change requires a new image
    Init Container Download Retrieves a model before the API container starts Requires identity, integrity checks, retries, and shared storage
    Persistent Volume Provides an independently managed artifact location Requires storage, access, version, and rollout controls
    Model Server Separates model-serving behavior from application routing Adds service, protocol, scaling, and operational complexity

    Example Init Container Pattern

    spec:
      template:
        spec:
          initContainers:
            - name: model-downloader
              image: registry.example.com/ml/model-downloader:1.0.0
              args:
                - download
                - --model-version=1.0.0
                - --destination=/models/model.joblib
              volumeMounts:
                - name: model-files
                  mountPath: /models
    
          containers:
            - name: ml-api
              image: registry.example.com/ml/customer-churn-api:1.0.0
              env:
                - name: MODEL_PATH
                  value: /models/model.joblib
              volumeMounts:
                - name: model-files
                  mountPath: /models
                  readOnly: true
    
          volumes:
            - name: model-files
              emptyDir: {}
    Supply-chain requirement: The downloader must authenticate through approved identity, retrieve an immutable model version, verify integrity, and prevent readiness until the expected artifact is available.

    Service Accounts and Access

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: customer-churn-api
      namespace: ml-inference
    automountServiceAccountToken: false
    Least-privilege rule: If the application does not call the Kubernetes API, avoid mounting a Kubernetes API credential into the Pod.

    Access-Control Requirements

    • Separate deployment and runtime identities
    • Grant only required Kubernetes permissions
    • Restrict Secret access
    • Use approved workload identity for cloud resources
    • Audit administrative operations
    • Rotate credentials where credentials remain necessary
    • Review permissions regularly

    Network Policies

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: customer-churn-api-ingress
      namespace: ml-inference
    spec:
      podSelector:
        matchLabels:
          app.kubernetes.io/name: customer-churn-api
    
      policyTypes:
        - Ingress
    
      ingress:
        - from:
            - namespaceSelector:
                matchLabels:
                  access-to-ml-api: "true"
          ports:
            - protocol: TCP
              port: 8000
    Network-policy requirement: Enforcement depends on the cluster networking implementation. Validate the policy in the actual cluster and define egress controls where required.

    Pod Security Practices

    Workload Hardening

    • Use approved and scanned images
    • Run as a non-root user
    • Disable privilege escalation
    • Drop unnecessary capabilities
    • Use the default runtime security profile
    • Use a read-only root filesystem where possible
    • Mount only necessary files and directories
    • Set resource requests and limits
    • Restrict Service Account permissions
    • Restrict network communication
    • Avoid embedding secrets in images
    • Verify model and image integrity

    Kubernetes Observability

    Signal Examples
    Metrics CPU, memory, replicas, restarts, latency, traffic, and errors
    Logs Startup, validation, inference, dependency, and shutdown events
    Traces Request flow across gateway, API, feature services, and dependencies
    Events Scheduling, image pulling, probes, scaling, and eviction activity
    Profiles CPU and memory behavior during representative inference workloads
    kubectl get events \
      --namespace ml-inference \
      --sort-by=.metadata.creationTimestamp

    ML Observability Beyond Kubernetes

    Monitoring Area Example Measure
    Input Quality Missing, invalid, stale, and unsupported features
    Feature Drift Changes in production input distributions
    Prediction Drift Changes in scores, classes, or threshold selections
    Delayed Quality Performance after verified outcomes become available
    Group Performance Quality and selection patterns for appropriate groups
    Model Version Requests and outcomes associated with each model version
    Business Outcome Workflow completion, cost, benefit, complaints, and overrides
    Critical distinction: A healthy Pod can serve an inaccurate or inappropriate model. Kubernetes health monitoring must be combined with ML and business monitoring.

    Kubernetes Cost Considerations

    Cost Driver Possible Control
    Idle Replicas Select justified minimum capacity
    Oversized Requests Right-size using observed utilization and load tests
    Excessive Limits Align upper boundaries with realistic workload behavior
    GPU Nodes Use accelerators only when evidence justifies them
    Unused Environments Apply ownership, expiration, and cleanup controls
    Observability Volume Control retention, sampling, labels, and cardinality
    Image Size Use focused and optimized runtime images
    Cross-Region Traffic Place services and data according to the approved architecture

    Troubleshooting Kubernetes ML Workloads

    Symptom Possible Investigation
    Pending Pod Resources, node selectors, affinity, taints, quotas, and storage
    ImagePullBackOff Image name, tag, registry identity, permissions, and network
    CrashLoopBackOff Startup command, logs, configuration, artifact loading, and permissions
    OOMKilled Model size, peak memory, worker count, batch size, and memory limit
    Readiness Failure Model initialization, dependencies, endpoint path, timeout, and probe timing
    Service Has No Endpoints Selector labels and Pod readiness
    Connection Refused Application binding, container port, Service target port, and policy
    Uneven Latency Replica resources, model warm-up, node placement, and dependencies
    HPA Does Not Scale Metrics availability, resource requests, target reference, and observed load
    Prediction Mismatch Image, model, threshold, dependencies, schema, and feature order
    kubectl describe pod \
      replace-with-pod-name \
      --namespace ml-inference
    
    kubectl logs \
      replace-with-pod-name \
      --namespace ml-inference
    
    kubectl get events \
      --namespace ml-inference \
      --sort-by=.metadata.creationTimestamp

    Kubernetes in CI/CD

    Release Flow
    Code Review → Tests → Build Image → Scan and Sign → Publish → Deploy Candidate → Smoke Test → Approve → Promote
    Gate Required Evidence
    Manifest Validation Schema, policy, and configuration checks
    Artifact Integrity Approved model version and checksum
    Image Security Base-image, package, secret, and configuration review
    Deployment Test Successful scheduling, startup, readiness, and smoke prediction
    Load Test Measured latency, throughput, resources, and scaling behavior
    Approval Authorized release decision
    Post-Release Validation Availability, latency, errors, version, and prediction comparison
    Rollback Validation Verified previous revision and recovery procedure

    GitOps for Kubernetes

    GitOps uses version-controlled declarative configuration as the desired deployment state. An authorized controller can reconcile the cluster with approved repository changes.

    GitOps Requirements

    • Version-controlled manifests
    • Protected branches
    • Peer review and approval
    • Automated policy and schema checks
    • No plaintext secrets in Git
    • Immutable image references
    • Drift detection
    • Auditable promotions
    • Documented rollback procedures
    GitOps limitation: Automated reconciliation does not determine whether a model is accurate, fair, safe, or approved. Model-governance gates must remain part of the release process.

    Responsible Kubernetes ML

    Responsible-Use Requirements

    • Deploy only approved model versions
    • Preserve validated preprocessing and thresholds
    • Return model and application versions
    • Protect input and prediction data
    • Restrict endpoint and cluster access
    • Document intended and prohibited uses
    • Communicate uncertainty
    • Provide human review for consequential decisions
    • Monitor relevant operating groups
    • Support correction of source data
    • Retain fallback and rollback capabilities
    • Retire vulnerable and obsolete workloads
    Incorrect Assumption A self-healing Kubernetes deployment guarantees correct Machine Learning predictions.
    Correct Understanding Kubernetes can maintain the serving workload, while separate ML controls validate inputs, predictions, drift, fairness, and downstream outcomes.

    Common Kubernetes Mistakes

    Mistake Deploy an image using only the mutable latest tag.
    Correction Use an immutable version and record the image digest and model version.
    Mistake Omit resource requests and limits.
    Correction Measure the workload and define tested scheduling and runtime boundaries.
    Mistake Use liveness and readiness interchangeably.
    Correction Use readiness to control traffic and liveness to identify a container that requires restart.
    Mistake Store plaintext Secrets in the repository.
    Correction Use the approved secret-management and workload-identity design.
    Mistake Autoscale without meaningful resource requests or load testing.
    Correction Define tested requests and select metrics that represent the actual ML inference bottleneck.
    Mistake Monitor Pod uptime but ignore model quality.
    Correction Monitor infrastructure, service, input, prediction, delayed quality, group performance, and business outcomes.
    Mistake Delete a Namespace without reviewing its contents.
    Correction Inspect ownership, environment, dependencies, and contained resources before any destructive command.

    Clean Up Learning Resources

    kubectl delete \
      --filename hpa.yaml \
      --filename pod-disruption-budget.yaml \
      --filename service.yaml \
      --filename deployment.yaml \
      --filename configmap.yaml \
      --namespace ml-inference
    kubectl delete namespace \
      ml-inference
    Deletion warning: Delete only authorized learning resources. Removing a Namespace can remove many resources within that scope.

    Recommended Kubernetes Workflow

    1

    Prepare the Approved Image

    Build, test, scan, version, and publish the ML API image to an approved registry.

    2

    Define the Workload Scope

    Select the cluster, Namespace, identity, labels, network, ownership, and environment.

    3

    Configure the Application

    Separate non-sensitive configuration from protected sensitive values.

    4

    Create the Deployment

    Define replicas, image, ports, resources, probes, security, and rollout strategy.

    5

    Create Stable Networking

    Use a Service and approved gateway or Ingress design where external access is required.

    6

    Validate the Workload

    Inspect scheduling, logs, probes, endpoints, resources, permissions, and prediction consistency.

    7

    Test Capacity and Scaling

    Load-test the service and configure replicas and autoscaling from measured behavior.

    8

    Release Gradually

    Use rolling, blue-green, canary, or another approved rollout strategy.

    9

    Monitor Operations and ML

    Track infrastructure, service, data, prediction, delayed quality, business outcomes, and cost.

    10

    Maintain and Retire

    Patch, update, roll back, remove obsolete workloads, and preserve traceability throughout the lifecycle.

    Hands-On Practice

    1

    Create a Namespace

    Define a dedicated development scope for the ML inference workload.

    2

    Create Configuration Resources

    Store non-sensitive settings in a ConfigMap and use an approved process for sensitive values.

    3

    Deploy the ML API

    Create a Deployment with two replicas, probes, resources, and non-root security controls.

    4

    Create the Service

    Provide stable internal access and confirm that ready Pods become Service endpoints.

    5

    Test Inference

    Port-forward the Service and test health, readiness, valid predictions, and invalid requests.

    6

    Configure Autoscaling

    Apply an HPA and inspect its behavior under controlled load.

    7

    Practice Update and Rollback

    Deploy a new immutable image version, monitor its rollout, and restore the previous revision.

    8

    Troubleshoot a Failure

    Introduce a safe development-only configuration error and use descriptions, events, logs, and status to diagnose it.

    Knowledge Check

    1

    What is container orchestration?

    Explain scheduling, replication, networking, health management, updates, and configuration across container workloads.

    2

    What is a Kubernetes Pod?

    Explain how it is an execution unit containing one or more tightly related containers.

    3

    Why use a Deployment instead of creating Pods directly?

    Explain desired replicas, replacement, revisions, rolling updates, and rollback.

    4

    Why is a Service required?

    Explain stable discovery and traffic routing to changing ready Pods.

    5

    What is the difference between readiness and liveness?

    Explain traffic eligibility versus container restart decisions.

    6

    Why define resource requests?

    Explain scheduling, capacity planning, and resource-utilization autoscaling.

    7

    What does an HPA do?

    Explain how it adjusts workload replicas according to configured observed metrics and replica boundaries.

    8

    Why use immutable image versions?

    Explain traceability, reproducibility, investigation, controlled promotion, and rollback.

    9

    Why is Kubernetes monitoring insufficient for ML quality?

    Explain that healthy infrastructure does not prove accurate, fair, or useful predictions.

    10

    Why must rollback be tested?

    Explain that revision history alone does not prove successful restoration, readiness, compatibility, or prediction behavior.

    Kubernetes Readiness Checklist

    Confirm Before Production Release

    • The model and container image are approved
    • The image uses an immutable version and recorded digest
    • The model version and threshold are traceable
    • The target cluster and Namespace are approved
    • Labels and selectors are consistent
    • Non-sensitive configuration uses approved configuration resources
    • Secrets are not committed to source control
    • The runtime Service Account has minimum permissions
    • The Pod runs as non-root
    • Privilege escalation is disabled
    • Unnecessary capabilities are removed
    • The root filesystem is read-only where supported
    • CPU and memory requests are measured
    • Resource limits are tested
    • Startup, readiness, and liveness probes are configured
    • The Service routes only to ready Pods
    • Network access is restricted appropriately
    • Prediction consistency has been verified
    • Invalid input is rejected safely
    • Autoscaling is based on meaningful signals
    • Scaling behavior has been load-tested
    • Replica placement supports availability requirements
    • Logs exclude sensitive payloads
    • Metrics, logs, traces, and alerts have owners
    • ML input, prediction, and delayed-quality monitoring is configured
    • Rollout and rollback procedures are tested
    • Responsible-use requirements are documented
    • Cost ownership and cleanup procedures are defined

    Lesson Summary

    Kubernetes Area Main Outcome
    Cluster Provides the control plane and worker-node infrastructure
    Pod Runs the containerized ML API
    Deployment Manages replicas, updates, revisions, and rollback
    Service Provides stable access to ready Pods
    ConfigMap Stores non-sensitive application configuration
    Secret Represents protected sensitive configuration
    Probes Control startup, traffic eligibility, and restart decisions
    Resource Controls Support scheduling, stability, capacity, and scaling
    HPA Adjusts replicas according to observed metrics
    Security Context Reduces runtime privileges
    Network Policy Restricts supported Pod communication
    Rolling Update Introduces an immutable application version gradually
    Rollback Restores an earlier approved Deployment revision
    Observability Supports diagnosis through metrics, logs, traces, and events
    ML Monitoring Tracks input, prediction, quality, group, and business behavior

    Key Takeaway

    Kubernetes orchestration operates containerized Machine Learning services through declarative resources and continuous reconciliation. A Deployment maintains the required Pods, a Service provides stable access, ConfigMaps and protected secret mechanisms provide configuration, probes manage startup and traffic readiness, resource controls support scheduling, and autoscaling adjusts capacity according to observed demand. A production-ready ML workload also requires immutable images, non-root execution, least-privilege identity, network restrictions, secure artifact distribution, rolling updates, tested rollback, infrastructure observability, and separate monitoring of data, predictions, delayed model quality, fairness, and business outcomes. Kubernetes can keep the inference platform running, but responsible ML controls ensure that the predictions remain valid and appropriate.

    Get Machine Learning updates by email

    Short, practical lessons and course updates from Rumman Ansari. No spam.