Kubernetes Objects for MLOps: From Pods to Production Deployments
From the publisher’s feed, collected in the ZeroLabs newsroom.
ai-generatedHow Deployments, Services, Jobs, configuration, storage, autoscaling, and scheduling turn a containerized model into a production service.Part 3 of the Kubernetes for MLOps seriesTL;DRKubernetes objects describe how an application should behave.The most important ones are:Pod: runs the application containersDeployment: manages stateless replicas and rolling updatesStatefulSet: provides stable identity and storageDaemonSet: runs one Pod on every selected nodeJob: executes finite workCronJob: creates Jobs on a scheduleService: gives changing Pods a stable endpointConfigMap: stores non-sensitive configurationSecret: provides credentials and sensitive valuesPersistentVolumeClaim: requests durable storageHPA: changes the number of replicasNamespace: groups resources and policiesNetworkPolicy: restricts Pod communicationIn production, you rarely create Pods or ReplicaSets directly. You usually create controllers such as Deployments, StatefulSets, and Jobs.Teams often package Kubernetes manifests with Helm, extend the platform with Custom Resource Definitions (CRDs), and use Operators to automate complex lifecycle tasks such as upgrades, backups, scaling, and recovery.For LLM workloads, configuration and model distribution require a different approachesThe Kubernetes Object StructureMost Kubernetes manifests begin with the same fields:apiVersion: apps/v1kind: Deploymentmetadata: name: fraud-detector namespace: ml-servingspec: replicas: 3apiVersion selects the API version.kind identifies the object.metadata gives it a name, namespace, labels, and annotations.spec describes the behaviour you want Kubernetes to maintain.The structure remains similar whether you create a Deployment, Service, Job, or ConfigMap.Pod: Where the Model/Application RunsA Pod is the smallest unit Kubernetes schedules.It can contain one or more containers that share:one Pod IP addressthe same network namespaceaccess through localhostand selected storage volumesFor the fraud detector, a Pod may include:an init container that retrieves the modelthe FastAPI inference containerand an optional telemetry or proxy sidecarMost application Pods should still contain one main container. Add another container only when it genuinely needs the same network, storage, and lifecycle.Init ContainersAn init container runs before the application starts.For model serving, it can retrieve a model from an artifact repository and write it into a shared volume:initContainers: - name: download-model image: registry.example.com/model-fetcher:1.0 args: - download - --model=fraud-detector-v3 - --output=/model/model.json volumeMounts: - name: model mountPath: /modelThe inference container mounts the same volume:containers: - name: fraud-detector image: registry.example.com/fraud-detector:2.1.0 volumeMounts: - name: model mountPath: /model readOnly: true volumes: - name: model emptyDir: {}emptyDir works well for files that can be recreated when the Pod starts. It disappears when the Pod is removed.For large models, downloading the artifact during every startup can slow down deployments and autoscaling. Consider image-based models, node-level caching, or a dedicated model-serving system when startup time becomes a problem.Resource Requests and LimitsEvery production workload should declare its expected CPU and memory usage.resources: requests: cpu: 500m memory: 512Mi limits: cpu: 1000m memory: 1GiRequests help the scheduler find a node with enough capacity.Limits restrict how much the container may consume.Memory usage above the limit can terminate the container. CPU limits can introduce throttling, so they should be tested carefully for latency-sensitive inference services.The correct values should come from load tests and production measurements.Health probes were covered in Part 2. In the Deployment below, we will simply reuse separate startup, readiness, and liveness endpoints.Choose the Right ControllerYou should rarely create a bare Pod in production.Instead, choose the controller that matches the workload.Use a Deployment for a stateless API.Use a StatefulSet when instances need stable names or persistent volumes.Use a DaemonSet for software that must run on every selected node.Use a Job for finite work such as training, evaluation, or batch inference.Use a CronJob when that finite work must run on a schedule.ReplicaSets maintain the requested number of Pods, but Deployments usually create and manage them automatically.Deployment: Running the Fraud-Detection APIA Deployment is the standard controller for stateless applications.It manages:the desired replica countreplacement Podsrolling updatesrollout historyand rollbackWhen the Pod template changes, the Deployment creates a new ReplicaSet and gradually replaces the previous version.Here is a practical Deployment for the fraud detector:apiVersion: apps/v1kind: Deploymentmetadata: name: fraud-detector namespace: ml-serving labels: app.kubernetes.io/name: fraud-detector app.kubernetes.io/component: inference-apispec: replicas: 3 revisionHistoryLimit: 5 selector: matchLabels: app.kubernetes.io/name: fraud-detector strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 template: metadata: labels: app.kubernetes.io/name: fraud-detector app.kubernetes.io/version: "2.1.0" model-version: "3" spec: terminationGracePeriodSeconds: 30 topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app.kubernetes.io/name: fraud-detector initContainers: - name: download-model image: registry.example.com/model-fetcher:1.0 args: - download - --model=fraud-detector-v3 - --output=/model/model.json volumeMounts: - name: model mountPath: /model resources: requests: cpu: 100m memory: 128Mi containers: - name: fraud-detector image: registry.example.com/fraud-detector:2.1.0 ports: - name: http containerPort: 8080 env: - name: MODEL_PATH value: /model/model.json - name: FEATURE_STORE_URL valueFrom: configMapKeyRef: name: fraud-detector-config key: feature_store_url - name: FEATURE_STORE_API_KEY valueFrom: secretKeyRef: name: fraud-detector-secrets key: feature_store_api_key resources: requests: cpu: 500m memory: 512Mi limits: memory: 1Gi volumeMounts: - name: model mountPath: /model readOnly: true startupProbe: httpGet: path: /health/startup port: http periodSeconds: 5 failureThreshold: 60 readinessProbe: httpGet: path: /health/ready port: http periodSeconds: 10 livenessProbe: httpGet: path: /health/live port: http periodSeconds: 30 securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL volumes: - name: model emptyDir: {} securityContext: runAsNonRoot: true seccompProfile: type: RuntimeDefaultThis manifest includes only the essential production settings:multiple replicascontrolled rolling updatesmodel initializationexternalized configurationresource requestshealth checksreplica distributiongraceful shutdownand a basic container security contextRolling UpdatesThese settings control the rollout:maxSurge: 1maxUnavailable: 0maxSurge: 1 allows one additional Pod during the update.maxUnavailable: 0 prevents the Deployment from intentionally reducing available capacity below the desired replica count.A safe rollout still depends on:correct readiness probesenough capacity for the additional Podgraceful request terminationand compatibility between application versions.Useful commands:kubectl rollout status deployment/fraud-detector -n ml-servingkubectl rollout history deployment/fraud-detector -n ml-servingkubectl rollout undo deployment/fraud-detector -n ml-servingPrefer versioned image tags or immutable image digests. Avoid reusing the same tag for different image contents.Other Controllers You Will Use in MLOpsStatefulSetA StatefulSet gives Pods stable names:feature-cache-0feature-cache-1feature-cache-2It can also create one persistent volume claim for each Pod.Use it for systems that need stable identity or dedicated storage, such as databases, queues, or distributed caches.A StatefulSet commonly works with a headless Service:apiVersion: v1kind: Servicemetadata: name: feature-cache-headless namespace: ml-servingspec: clusterIP: None selector: app: feature-cache ports: - name: cache port: 6379StatefulSet handles identity, ordering, and storage attachment.It does not automatically configure data replication, backups, leader election, or disaster recovery. Those responsibilities belong to the application, an operator, or a managed platform.DaemonSetA DaemonSet runs one Pod on every eligible node.Typical examples include:log collectorsnode metrics agentssecurity agentsnetwork componentsand hardware-monitoring exportersA node selector can restrict it to accelerator nodes:spec: template: spec: nodeSelector: accelerator: gpuWhen another matching node joins the cluster, the DaemonSet automatically creates a Pod on it.JobA Job runs work until it completes successfully.MLOps examples include:model trainingbatch inferencefeature backfillsdata validationand model evaluationAn Indexed Job can split a large dataset into several shards:apiVersion: batch/v1kind: Jobmetadata: name: fraud-batch-scoring namespace: ml-trainingspec: completions: 20 parallelism: 5 completionMode: Indexed backoffLimit: 3 activeDeadlineSeconds: 14400 ttlSecondsAfterFinished: 86400 template: spec: restartPolicy: Never containers: - name: scorer image: registry.example.com/fraud-batch-scorer:2.1.0 args: - --shard-index=$(JOB_COMPLETION_INDEX) - --total-shards=20 - --input=/datasets/transactions - --output=/results/fraud-scorescompletions: 20 creates twenty logical tasks.parallelism: 5 allows five to run at the same time.Batch processing should be idempotent because retries or duplicate execution can occur during failures.CronJobA CronJob creates Jobs on a schedule.For example, the team may evaluate the fraud model every night:apiVersion: batch/v1kind: CronJobmetadata: name: fraud-model-evaluation namespace: ml-trainingspec: schedule: "0 2 * * *" timeZone: "Etc/UTC" concurrencyPolicy: Forbid startingDeadlineSeconds: 3600 successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 5 jobTemplate: spec: template: spec: restartPolicy: Never containers: - name: evaluator image: registry.example.com/fraud-model-evaluator:2.1.0 args: - --evaluate-previous-day - --minimum-score=0.92concurrencyPolicy: Forbid prevents a second evaluation from starting while the previous one is still running.CronJobs are useful for simple schedules. Complex training pipelines may require an orchestration system for dependencies, retries, approvals, lineage, and quality gates.Service: A Stable Endpoint for Changing PodsPods are replaceable, and their IP addresses change.A Service gives clients a stable DNS name and virtual address.apiVersion: v1kind: Servicemetadata: name: fraud-detector namespace: ml-servingspec: selector: app.kubernetes.io/name: fraud-detector ports: - name: http port: 80 targetPort: http type: ClusterIPThe selector connects the Service to Pods carrying this label:app.kubernetes.io/name: fraud-detectorWhen Pods are created or replaced, Kubernetes updates the Service backends automatically.The application can be reached inside the cluster through a name such as:fraud-detector.ml-serving.svc.cluster.localService TypesUse ClusterIP for internal application communication.Use LoadBalancer when your infrastructure integration should expose a Service externally.Use NodePort mainly when another infrastructure component requires it.Use ExternalName to create a DNS alias for an external service.Use a headless Service when clients need the individual addresses of StatefulSet Pods.For HTTP routing, TLS, hostnames, and paths, place a Gateway or Ingress controller in front of the Service:Client ↓Gateway or Ingress ↓Service ↓Ready PodsThe exact routing configuration depends on the controller installed in your clusterConfigMap: Application ConfigurationA ConfigMap stores non-sensitive values outside the container image.apiVersion: v1kind: ConfigMapmetadata: name: fraud-detector-config namespace: ml-servingdata: feature_store_url: "redis://feature-cache.ml-serving:6379" fraud_score_threshold: "0.85" log_level: "INFO"The Deployment can reference one key:env: - name: FRAUD_SCORE_THRESHOLD valueFrom: configMapKeyRef: name: fraud-detector-config key: fraud_score_thresholdThis allows the same image to run with different settings in development, staging, and production.Environment variables do not change inside a running process when the ConfigMap is updated. A new Pod or rollout is normally required.ConfigMaps can also be mounted as files, but the application must reread the file to observe updates.Secret: Sensitive ConfigurationA Secret provides values such as:API tokenspasswordsTLS keysand registry credentialsReference it from the Pod rather than writing the value into the Deployment:env: - name: FEATURE_STORE_API_KEY valueFrom: secretKeyRef: name: fraud-detector-secrets key: feature_store_api_keyBase64 encoding is not encryption.Production secret management should include:encryption at restrestricted RBAC accesssecret rotationprotected backupsno credentials in Gitand no secret values in logsAn external secret-management ( gcp sercret manager for example ) integration can keep the source credentials outside the application repository.Namespace, Labels, and QuotasNamespaceNamespaces group related resources.A simple MLOps organization could use:ml-serving for inference applicationsml-training for training and batch Jobsml-experiments for experimentationdata-pipelines for feature pipelinesmonitoring for observabilityA Namespace does not automatically provide complete security or network isolation.Policies such as RBAC, ResourceQuota, and NetworkPolicy create those boundaries.LabelsLabels connect Kubernetes objects.metadata: labels: app.kubernetes.io/name: fraud-detector app.kubernetes.io/version: "2.1.0" app.kubernetes.io/component: inference-api model-version: "3" environment: production team: ml-platformDeployments use labels to identify Pods.Services use them to find backends.NetworkPolicies use them to select protected workloads.You can also query them:kubectl get pods \ -n ml-serving \ -l app.kubernetes.io/name=fraud-detectorUse a consistent label vocabulary across your platform.ResourceQuotaA ResourceQuota limits total consumption inside a Namespace:apiVersion: v1kind: ResourceQuotametadata: name: ml-serving-quota namespace: ml-servingspec: hard: requests.cpu: "32" requests.memory: 64Gi limits.memory: 128Gi pods: "50"Quotas prevent one workload or team from consuming all shared cluster capacity.A LimitRange can also provide default resource requests and limits when a workload omits them.Persistent StorageContainer filesystems and emptyDir volumes are temporary.For durable data, workloads request storage through a PersistentVolumeClaim:apiVersion: v1kind: PersistentVolumeClaimmetadata: name: training-checkpoints namespace: ml-trainingspec: accessModes: - ReadWriteOnce storageClassName: fast-storage resources: requests: storage: 200GiThe training container mounts the claim:volumeMounts: - name: checkpoints mountPath: /checkpointsvolumes: - name: checkpoints persistentVolumeClaim: claimName: training-checkpointsA StorageClass describes how the underlying volume is provisioned:apiVersion: storage.k8s.io/v1kind: StorageClassmetadata: name: fast-storageprovisioner: storage.example.com/csi #GCP for examplereclaimPolicy: DeleteallowVolumeExpansion: truevolumeBindingMode: WaitForFirstConsumerThe provisioner is specific to your installed CSI driver.WaitForFirstConsumer lets Kubernetes consider the consuming Pod’s placement before binding or creating the volume.Use persistent volumes for workloads such as checkpoints or database storage.Large datasets and model artifacts are often better placed in object storage, an artifact repository, or a distributed filesystem.Horizontal AutoscalingThe HorizontalPodAutoscaler changes the replica count of a Deployment.apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: fraud-detector namespace: ml-servingspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: fraud-detector minReplicas: 3 maxReplicas: 30 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 behavior: scaleDown: stabilizationWindowSeconds: 300CPU-based HPA requires CPU requests because utilization is calculated relative to the request.For inference services, demand may be represented better by:requests per secondqueue depthactive requestspending batchesor accelerator utilizationThose metrics require a compatible metrics adapter.Remember that HPA creates Pods, not nodes. When the cluster lacks capacity, additional replicas remain Pending.Scheduling on the Right HardwareTraining and inference often need different node types.Node affinity lets a Pod request nodes with particular labels:affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: accelerator operator: In values: - gpuTaints prevent unrelated workloads from using specialized nodes:kubectl taint node accelerator-node-1 \ dedicated=accelerator:NoScheduleThe intended workload adds a matching toleration:tolerations: - key: dedicated operator: Equal value: accelerator effect: NoScheduleA toleration permits placement on the node. It does not require it.Use affinity or hardware resource requests as well when the Pod must run there.Spread Replicas Across NodesRunning every fraud-detector replica on the same worker node creates a single point of failure.Topology spread constraints distribute them:topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app.kubernetes.io/name: fraud-detectorThis configuration asks Kubernetes to keep the replica distribution balanced across nodes.It is generally more flexible for autoscaling workloads than requiring exactly one matching Pod per node.NetworkPolicy: Restrict CommunicationNetworkPolicy defines which traffic selected Pods may send or receive.Enforcement requires a network implementation that supports NetworkPolicy.A strong starting point is default deny:apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: default-deny namespace: ml-servingspec: podSelector: {} policyTypes: - Ingress - EgressAfter applying it, create explicit allow policies for required traffic:Gateway to fraud-detector Podsfraud detector to the feature storePods to cluster DNSmonitoring systems to metrics endpointsStandard NetworkPolicies are additive. Build them as small allowlists rather than attempting to maintain one large rule.The source article similarly recommends a default-deny posture followed by explicit allow policies.Final Mental ModelThink of Kubernetes objects in four groups.ExecutionPods run containers.LifecycleDeployments, StatefulSets, DaemonSets, Jobs, and CronJobs decide how Pods are created and replaced.Connectivity and configurationServices, ConfigMaps, Secrets, and volumes connect workloads to traffic, settings, credentials, and data.Platform controlNamespaces, quotas, autoscalers, scheduling rules, and NetworkPolicies control capacity, placement, scaling, and isolation.The goal is not to memorize every YAML field.The useful question is:What behaviour should Kubernetes maintain for this workload?Then choose the object that expresses that behaviour.A Docker image gives you a packaged application.Kubernetes objects turn that image into a managed ML service.References and Further ReadingKubernetes Workloadshttps://kubernetes.io/docs/concepts/workloads/Deploymentshttps://kubernetes.io/docs/concepts/workloads/controllers/deployment/Serviceshttps://kubernetes.io/docs/concepts/services-networking/service/ConfigMaps and Secretshttps://kubernetes.io/docs/concepts/configuration/Horizontal Pod Autoscalinghttps://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/Kubernetes Objects for MLOps: From Pods to Production Deployments was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.