Docker and Kubernetes for Machine Learning Workloads
A model that runs on a laptop but fails in the data center is not deployed â it is demoed. Environment drift, missing system libraries, GPU driver mismatches, and "it worked in the notebook" are the same root cause: the artifact shipped without its runtime. Containers solve this by packaging code, dependencies, and system libraries into an immutable image; orchestration platforms like Kubernetes then run those images reliably across fleets with scheduling, scaling, and rollouts.
This lesson is ML-specific. You will build a training image and an inference image (they differ more than people expect), push them to a registry, and run them on Kubernetes â including GPU scheduling, health probes, resource requests, and rolling updates. The goal is a path from "notebook works" to "cluster serves traffic" that does not depend on any single machine's state.
What You'll Learn
- 1Write multi-stage Dockerfiles that keep inference images small and training images reproducible
- 2Manage GPU resources, requests, and limits in Kubernetes pod specs
- 3Deploy model serving behind a Service and Ingress with health probes
- 4Perform zero-downtime rollouts with readiness checks and resource budgets
Prerequisites
- !Comfortable with the command line and Linux basics
- !Python packaging and virtual environments
- !Familiarity with YAML and REST APIs
Why notebooks lie about production environments
Notebooks run in an interactive kernel with a shell, a mounted filesystem, and whatever packages the user installed ad hoc over months. Production jobs run in a minimal image, often as a non-root user, with no internet access during execution and ephemeral storage. The gap shows up as missing shared libraries (a wheel that quietly expected system BLAS), path assumptions (/Users/alice/data), and version conflicts that pip resolved interactively but not from a clean lockfile.
Containers close the gap by making the environment an artifact you build once, tag immutably, and deploy everywhere. The discipline that matters is treating the Dockerfile as source: reviewed, versioned, and built by CI â not assembled by hand on a GPU box and forgotten.
| Concern | Training image | Inference image |
|---|---|---|
| Base size | GBs acceptable (CUDA, data tools) | MBs to low GBs (latency, cold start) |
| Included frameworks | Full stack (PyTorch, DVC, profiling) | Minimal (runtime + serving stack) |
| Entry point | Job script, checkpointing | Long-running HTTP/gRPC server |
| User | Often non-root, read-only data mounts | Non-root, read-only rootfs preferred |
| Restart policy | Job completes or retries | CrashLoopBackOff must self-heal |
Building a training image with multi-stage Docker
Multi-stage builds keep build tools out of the final image. A builder stage compiles wheels and installs heavy frameworks; a runtime stage copies only what the job needs. For training, reproducibility beats minimalism â pin versions and record the build metadata.
# syntax=docker/dockerfile:1.6
FROM python:3.11-slim AS builder
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential git libgomp1 && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim AS runtime
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
PATH="/opt/venv/bin:$PATH" HF_HOME=/cache/huggingface
RUN apt-get update && apt-get install -y --no-install-recommends \
libgomp1 curl && rm -rf /var/lib/apt/lists/* \
&& groupadd -r ml && useradd -r -g ml -d /app ml
COPY --from=builder /opt/venv /opt/venv
WORKDIR /app
COPY train.py ./train.py
COPY src/ ./src/
USER ml
ENTRYPOINT ["python", "train.py"]
# requirements.txt (excerpt â pin exactly)
torch==2.4.0
transformers==4.44.0
datasets==2.21.0
scikit-learn==1.5.1
numpy==1.26.4
Build and push with immutable tags â never latest in production:
docker build --target runtime -t registry.example.com/ml/train:1.4.2 .
docker push registry.example.com/ml/train:1.4.2
docker run --rm --gpus all \
-v /mnt/datasets:/data:ro \
registry.example.com/ml/train:1.4.2 --epochs 3
The :ro data mount enforces read-only access to training data â a cheap guard against accidental writes corrupting a shared store. Record the git commit and data snapshot as labels in the image (--label git.sha=$GIT_SHA) so a running pod is always traceable to source.
Serving image: strip everything you can
Inference images care about cold start and attack surface. Drop training-only libraries, compile the model where possible, and run as non-root with a read-only filesystem.
# syntax=docker/dockerfile:1.6
FROM python:3.11-slim AS builder
ENV PIP_NO_CACHE_DIR=1
WORKDIR /build
COPY serving-requirements.txt .
RUN python -m venv /opt/venv && \
/opt/venv/bin/pip install --no-cache-dir -r serving-requirements.txt
FROM python:3.11-slim AS runtime
ENV PYTHONUNBUFFERED=1 PATH="/opt/venv/bin:$PATH" \
PORT=8080 HOME=/tmp
RUN groupadd -r serve && useradd -r -g serve -d /app serve \
&& mkdir -p /app/model && chown -R serve:serve /app
COPY --from=builder /opt/venv /opt/venv
WORKDIR /app
COPY serve.py .
COPY --chown=serve:serve model/ /app/model/
USER serve
EXPOSE 8080
HEALTHCHECK --interval=15s --timeout=3s --retries=3 \
CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1
CMD ["python", "serve.py"]
# serve.py â minimal FastAPI entrypoint
import os
import pandas as pd
import mlflow.pyfunc
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="churn-classifier")
model = mlflow.pyfunc.load_model(os.environ["MODEL_URI"])
class Row(BaseModel):
features: list[float]
@app.get("/healthz")
def healthz():
return {"ok": True}
@app.post("/predict")
def predict(rows: list[Row]):
try:
df = pd.DataFrame([r.features for r in rows])
out = model.predict(df)
return {"predictions": out.to_dict(orient="records")}
except Exception as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
Split /healthz (liveness: process alive) from /readyz (readiness: model loaded, dependencies reachable). Kubernetes restarts on liveness failure and stops routing traffic on readiness failure â conflating them causes restart storms when a model download is merely slow.
Kubernetes basics for ML pods
A Deployment declares desired state; the kube-scheduler places pods on nodes matching resource requests; a Service provides stable DNS and load balancing; an Ingress terminates TLS and routes by path. For ML, the critical YAML decisions are resource requests versus limits, GPU requests, and probe configuration.
apiVersion: apps/v1
kind: Deployment
metadata:
name: churn-classifier
labels: { app: churn-classifier }
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
selector:
matchLabels: { app: churn-classifier }
template:
metadata:
labels: { app: churn-classifier }
spec:
securityContext:
runAsNonRoot: true
seccompProfile: { type: RuntimeDefault }
containers:
- name: server
image: registry.example.com/ml/churn:2.1.0
ports: [{ containerPort: 8080 }]
env:
- name: MODEL_URI
value: models:/churn-classifier/Production
resources:
requests: { cpu: "500m", memory: "1Gi", nvidia.com/gpu: "1" }
limits: { cpu: "2", memory: "4Gi", nvidia.com/gpu: "1" }
readinessProbe:
httpGet: { path: /readyz, port: 8080 }
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet: { path: /healthz, port: 8080 }
initialDelaySeconds: 30
periodSeconds: 20
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: ["ALL"] }
volumeMounts:
- { name: tmp, mountPath: /tmp }
volumes:
- name: tmp
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
name: churn-classifier
spec:
selector: { app: churn-classifier }
ports: [{ port: 80, targetPort: 8080 }]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: churn-classifier
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls: [{ hosts: [ml.example.com], secretName: ml-tls }]
rules:
- host: ml.example.com
http:
paths:
- path: /churn
pathType: Prefix
backend:
service:
name: churn-classifier
port: { number: 80 }
readOnlyRootFilesystem: true with an emptyDir on /tmp keeps the container immutable while giving the process a writable scratch space. Requests guarantee scheduling capacity; limits cap abuse. CPU-only inference often needs requests: 500m and serves hundreds of QPS â over-requesting wastes cluster budget.
GPU scheduling and node pools
GPUs are schedulable resources (nvidia.com/gpu) only when the device plugin is installed on the node. Isolate them onto dedicated node pools so batch training cannot starve online inference:
apiVersion: v1
kind: Pod
metadata: { name: nightly-train }
spec:
nodeSelector: { workload: training }
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
containers:
- name: train
image: registry.example.com/ml/train:1.4.2
resources:
requests: { cpu: "4", memory: "16Gi", nvidia.com/gpu: "1" }
limits: { cpu: "8", memory: "32Gi", nvidia.com/gpu: "1" }
volumeMounts:
- { name: datasets, mountPath: /data, readOnly: true }
volumes:
- name: datasets
persistentVolumeClaim: { claimName: datasets-pvc }
restartPolicy: Never
Kubernetes does not natively time-share GPUs well; one GPU request equals exclusive access to one device unless a sharing plugin (for example MIG or time-slicing) is configured. For multi-GPU distributed training, prefer a framework-aware operator (Ray, MPI, or a training operator) over hand-rolled pod coordination â checkpoint coordination and rank scheduling are subtle.
Rollouts, health, and rollback
maxUnavailable: 0 with maxSurge: 1 means the cluster starts a new pod, waits for readiness, then terminates an old one â zero-downtime if probes are honest. A bad image that crashes on boot will fail liveness, get restarted, and eventually CrashLoopBackOff without ever receiving traffic â provided readiness gates on /readyz, not just TCP connect.
# Watch the rollout; abort and roll back on failure
kubectl rollout status deployment/churn-classifier --timeout=300s
kubectl rollout undo deployment/churn-classifier
# Canary a new image on a slice of replicas via a second Deployment
kubectl set image deployment/churn-canary \
server=registry.example.com/ml/churn:2.2.0-rc1
For progressive delivery beyond manual canaries, layer a traffic splitter (Argo Rollouts, Flagger) that shifts a percentage of Service traffic to the new ReplicaSet and watches error-rate SLOs before full promotion. Pair it with the model registry from the previous lesson: promote models:/churn-classifier/Production only after the canary window closes green.
Cost and operational hygiene
Idle GPU node pools dominate ML cloud bills. Autoscale training jobs with cluster autoscaler on queue depth (Kueue or a simple job queue), and scale inference with Horizontal Pod Autoscaler on CPU or custom metrics (queue depth, tokens/sec) rather than leaving replicas pinned. Set terminationGracePeriodSeconds generously enough for graceful shutdown (finish in-flight requests, flush metrics) but not so long that rollouts crawl.
Tag every namespace and workload with team and cost-center labels; most cost-showback tooling keys off them. Finally, keep images small and scanned: a training image that never shrinks accumulates CVEs in libraries nobody imports anymore â rebuild on a schedule, not only when features change.
One pattern that ties cost and reliability together is the spot/preemptible instance with checkpointing for training. Spot instances cost a fraction of on-demand but can be reclaimed with short notice; a training job that checkpoints to persistent storage every epoch and resumes from the latest checkpoint on restart can ride spot capacity for 60â80% savings with bounded lost work. Inference endpoints almost never belong on spot â the cold-start cost of losing a loaded model mid-traffic usually exceeds the savings. Finally, treat the cluster itself as cattle: document a single command path (or Terraform module) that rebuilds the node pools, the ingress controller, and the GPU device plugin from source, because the first real disaster recovery will not wait for someone to remember which add-ons were installed by hand six months ago.
Common Mistakes
Using latest as the image tag in Deployments
Fix: Tag with immutable versions or git SHAs; latest makes rollbacks non-deterministic and hides what is actually running.
Setting only liveness probes, or gating readiness on TCP connect
Fix: Separate /healthz from /readyz; readiness must verify model load and dependency checks so traffic never reaches an unprepared pod.
Training and inference sharing one bloated image
Fix: Build separate images: training prioritizes reproducibility and full tooling; inference strips to runtime, serving stack, and model for fast cold starts.
Scheduling training and inference on the same GPU node pool
Fix: Use dedicated node pools with taints and tolerations so batch jobs cannot starve latency-sensitive serving of devices or CPU.
Best Practices
- Review Dockerfiles in PRs and build them in CI with provenance labels (git SHA, build time)
- Pin base images by digest and Python packages exactly in requirements or lockfiles
- Run as non-root, drop capabilities, and use readOnlyRootFilesystem with an emptyDir for scratch
- Set resource requests accurately; limits protect neighbors but requests decide scheduling
- Pair rollouts with readiness probes and automated rollback; add Argo Rollouts or Flagger for metric-gated promotion
Interview Questions
Q1: Why must readiness and liveness probes be separate endpoints?
Liveness answers 'should the kubelet restart this process?' â it must be shallow and dependency-free. Readiness answers 'can this instance serve traffic right now?' â it must check model load and downstream dependencies. Conflating them restarts pods that are merely waiting on a slow download, causing outages.
Q2: What do GPU resource requests and limits control on Kubernetes?
Requests determine scheduling â the scheduler places the pod on a node with a free GPU. Limits (equal to requests for GPUs by default) cap device access. Exclusive access is the norm unless a sharing plugin is configured.
Q3: How would you perform a zero-downtime model rollout?
RollingUpdate with maxUnavailable=0 and maxSurge=1, readiness gated on a /readyz that confirms the new model is loaded; or a canary Deployment with Argo Rollouts shifting traffic while watching error-rate SLOs, then full promotion.
Key Takeaways
- Multi-stage Dockerfiles separate build tooling from runtime; training images optimize for reproducibility, inference images for size and cold start
- Kubernetes Deployments plus Services plus Ingress give portable serving; requests/limits, probes, and security contexts are the ML-relevant YAML
- Dedicate GPU node pools with taints so training cannot starve inference of devices
- Zero-downtime rollouts require honest /readyz probes and maxUnavailable=0; pair with registry-gated promotion
- Cost control comes from autoscaling on real signals and strict image hygiene, not from leaving GPUs warm just in case