Containerizing ML Services with Docker and Kubernetes
Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe
Prerequisites
- !Writing a Dockerfile for a web service
- !Kubernetes objects such as Deployment and Service
- !How your model is loaded at startup
What You'll Learn
- 1Keep serving images small, reproducible, and non-root
- 2Choose probe and resource settings that match model warm-up
- 3Run rolling updates without dropping in-flight requests
- 4Schedule GPU workloads with correct requests and node selection
Why ML images bloat so fast
A typical first attempt at a model-serving image weighs four gigabytes: the base image ships a full CUDA toolkit the runtime never touches, pip install pulls in the entire training stack including Jupyter and plotting libraries, and the model weights get baked in with COPY . ., forcing a full rebuild whenever a checkpoint changes. Every one of those bytes slows the cold start that a pod must complete before it passes readiness, multiplies the attack surface your scanner complains about, and costs money on every node that has to pull it. Image size is not vanity in ML â it is time-to-ready multiplied by pull frequency.
The second problem is reproducibility. An image built from a mutable latest base and unpinned dependencies cannot be rebuilt six months later to investigate a bug, and a model that behaves differently from its own image is a support problem waiting to happen. Two disciplines fix both issues: multi-stage builds that separate build-time tooling from runtime contents, and a hard rule that the artifact â model and code â is versioned and referenced rather than copied in casually.
Anatomy of a serving image
The Dockerfile below follows three rules that matter for ML: build wheels in a builder stage so compilers never reach production, run as a non-root user because most clusters enforce it, and expose a readiness endpoint that reflects whether the model is actually loaded. The .dockerignore step that people skip â excluding training data, notebooks, and checkpoints from the build context â is often the single largest size win available.
# Dockerfile
FROM python:3.11-slim AS builder
WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends build-essential \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
FROM python:3.11-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
MODEL_PATH=/models/current/model.pkl
RUN useradd --create-home --uid 10001 --shell /usr/sbin/nologin serving
WORKDIR /app
COPY --from=builder /install /usr/local
COPY src/ ./src/
COPY configs/ ./configs/
USER serving
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).status==200 else 1)"
CMD ["python", "-m", "src.server"]
Note --start-period=60s in the health check. Models load slowly, and a container that is killed for failing health during warm-up enters a restart loop that looks like a crash but is really a misconfigured timeout. The same reasoning applies to your orchestrator's readiness probe: readiness should verify the model is loaded and the weights checksum matches, while liveness should touch nothing heavier than a counter.
Deployment, service, and autoscaling
Kubernetes objects for ML differ from a web service in three places: resource requests must reflect real memory use including the loaded weights, probes need warm-up grace, and the rolling update strategy must guarantee surge capacity so no request arrives at a pod that is still loading. The manifests below encode those, along with a horizontal autoscaler driven by CPU plus a custom queue-depth metric that better represents inference pressure.
# k8s/ml-serving.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: ml-server
namespace: production
labels:
app: ml-server
spec:
replicas: 3
selector:
matchLabels:
app: ml-server
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: ml-server
version: v3
spec:
serviceAccountName: ml-server
terminationGracePeriodSeconds: 60
containers:
- name: ml-server
image: registry.example.com/ml-server:3.4.1
ports:
- containerPort: 8000
env:
- name: MODEL_PATH
valueFrom:
configMapKeyRef:
name: ml-config
key: model-path
- name: MLFLOW_TRACKING_URI
valueFrom:
secretKeyRef:
name: ml-secrets
key: tracking-uri
resources:
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 4Gi
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 30
periodSeconds: 5
failureThreshold: 12
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 60
periodSeconds: 20
lifecycle:
preStop:
exec:
command: ["sleep", "15"]
volumeMounts:
- name: models
mountPath: /models
readOnly: true
volumes:
- name: models
persistentVolumeClaim:
claimName: model-store
---
apiVersion: v1
kind: Service
metadata:
name: ml-server
namespace: production
spec:
selector:
app: ml-server
ports:
- port: 80
targetPort: 8000
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: ml-server
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: ml-server
minReplicas: 3
maxReplicas: 20
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 4
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 65
- type: Pods
pods:
metric:
name: inference_queue_depth
target:
type: AverageValue
averageValue: "8"
The preStop sleep deserves explanation. Without it, the endpoint is removed from the service at the same instant the process begins shutting down, so requests already routed there fail. Fifteen seconds of draining lets the load balancer converge before the process exits, and it is the difference between a rollout nobody notices and one that shows up as a blip in your error rate.
Probes, requests, and limits
Choosing these numbers is a small measurement exercise rather than a matter of taste. Requests should equal steady-state usage so the scheduler places pods correctly; set them too low and the node oversubscribes, and every pod on it becomes slow simultaneously. Set them too high and you pay for idle capacity. Memory limits must include the loaded model plus runtime overhead â measure the resident set after warm-up, then add a thirty percent margin, because an OOM kill during a traffic spike looks exactly like a crash and destroys your availability numbers.
| Setting | Too low | Too high | How to set it |
|---|---|---|---|
| CPU request | Noisy neighbour interference | Idle capacity billed | Measure steady-state utilization per pod |
| Memory request | Eviction under pressure | Over-provisioned cluster | Resident set after model load, plus margin |
| Memory limit | Silent OOM kills | No protection at all | Slightly above peak resident set |
| Readiness delay | Warm-up restart loops | Slow traffic joining | Time the actual model load, plus margin |
| Liveness timeout | False restarts | Slow detection of real hangs | Should be longer than p99 handler time |
The asymmetry in that table is deliberate: over-estimating readiness delay costs a few seconds of added rollout time, while under-estimating it causes a restart loop that can take a service down entirely. When unsure, be generous with warm-up and strict with limits.
Rolling updates without dropped requests
A correct rollout needs four things to line up: surge capacity so a new pod starts before an old one stops, readiness gating so traffic only reaches pods that can serve, graceful termination so in-flight requests finish, and a verification step that decides whether the new version should continue. maxUnavailable: 0 plus maxSurge: 1 gives the first two; preStop plus a sufficient termination grace period gives the third.
The fourth is where teams most often stop short. Automated verification â a smoke test against the new pods, a canary percentage watched for guardrail breaches, then promotion â turns a rollout into a decision made by evidence rather than by whoever clicked deploy. Pair it with an image rollback that simply sets the previous digest, and a bad release becomes a five-minute event. Do not skip the rehearsal: deliberately ship a build that fails verification once, and learn whether your rollback path is thirty seconds or half an hour.
GPU scheduling quirks
GPU nodes need an extended resource declared so the scheduler understands them: nvidia.com/gpu is requested as an integer, cannot be over-committed, and is allocated whole to one container. A pod requesting one GPU receives exactly one; there is no way to ask for a quarter of a device, which makes GPU sharing a design decision involving time-slicing or a proxy service rather than a configuration flag.
Two operational habits save money here. First, separate GPU node pools from CPU pools with taints and tolerations, so an inference service never sits on capacity reserved for training. Second, set a priority class for training jobs so preemption cleans up experiments rather than production. The commonest GPU bill problem is not the hourly rate â it is pods that finished their work but never released the device because their request was still satisfied while idle.
â ī¸Never bake weights into a frequently rebuilt image
Common Mistakes
Copying training dependencies into the serving image
Fix: Pin a serving-only requirements file; if it is not imported at inference, it does not belong in the runtime stage.
Skipping preStop draining on rollout
Fix: Add a short preStop sleep and a termination grace period longer than your slowest in-flight request.
Setting memory limits from guesswork
Fix: Measure resident memory after model load, add margin, and verify under a load test before locking it in.
Running as root because it was faster to write
Fix: Create a dedicated non-root user in the runtime stage â most admission policies enforce it anyway.
Best Practices
- Use multi-stage builds and a tight .dockerignore
- Separate model artifacts from images and pin them by digest
- Gate readiness on actual model readiness, not on the process being alive
- Keep image tags immutable so rollback always resolves to known bytes
- Scan images in CI and block promotion on critical CVEs
Interview Questions
Q1: Why do ML serving images need special treatment?
Weights, CUDA libraries, and training dependencies inflate size, which directly increases cold-start time before readiness and enlarges the attack surface.
Q2: Readiness versus liveness for a model server?
Readiness verifies the model is loaded and consistent, keeping warming pods out of rotation; liveness only detects a wedged process, since restarting during warm-up causes loops.
Q3: How do you avoid dropped requests during rollout?
maxUnavailable zero with surge capacity, a preStop drain, and a termination grace period that covers the slowest request.
Q4: What is special about GPU requests in Kubernetes?
They are integer extended resources, never over-committed, assigned wholly to one container â so pooling and priority classes determine utilization.
Key Takeaways
- Image size equals time-to-ready on every pull â build lean and pin digests
- Readiness must reflect model state; liveness must stay cheap
- Drain before exit, surge before terminate, verify before promoting
- Measure resource requests from real usage, not from templates
- Keep weights out of the image so code and model cadences stay independent