Lab: Docker, Kubernetes, Streaming API and Capstone
A demo runs on your laptop. A service survives bad input, restarts, busy hours and the person who has to fix it at night.
You will turn an agent into a streaming web service with authentication, size, time and concurrency limits and health checks, test it, package it in a container, describe it for Kubernetes with restrictive settings, and finish with a capstone that joins the earlier labs.
What you will learn: server-sent events, smoke testing, safer container images, probes, resource and network settings, rollout and rollback.
Prerequisites: Set Up Your Agent Development Lab, Python and basic HTTP. Docker or a compatible tool for the container part; a test cluster for the optional cluster part. About 2 to 3 hours.
November 2026, Python 3.13, starlette 1.7.0, uvicorn 0.54.0, kubernetes-validate 1.37.0. The service and smoke test ran locally. The container was built and smoke-tested using a stand-in local base image, without network access, so downloading python:3.13-slim and installing packages inside the build were not tested. The manifests were checked against schemas only, never applied to a cluster. The "busy" (429) reply, client disconnects, the missing-token readiness reply and a shortened time limit were checked locally with a slower stand-in agent. The agent itself is a stand-in that calls no model.
Goal and shape
The lab builds the service and describes the rest. Make a folder with the files below and install:
python -m pip install "starlette==1.7.0" "uvicorn==0.54.0" httpx pyyaml "kubernetes-validate==1.37.0"
A streaming API
Agents take time, so send progress as it happens. Server-sent events keep one HTTP response open and send small named messages. Save as app.py:
"""A streaming agent API with health checks, authentication and limits."""
import asyncio
import hmac
import json
import os
from starlette.applications import Starlette
from starlette.responses import JSONResponse, StreamingResponse
from starlette.routing import Route
TOKEN = os.environ.get("API_TOKEN", "")
MAX_BODY, MAX_RUNNING = 4096, 4
running = asyncio.Semaphore(MAX_RUNNING)
async def agent_events(question):
"""Stand-in for the agent loop: yields progress, then the answer in pieces."""
yield "step", {"name": "lookup", "state": "started"}
await asyncio.sleep(0.05)
yield "step", {"name": "lookup", "state": "finished"}
for word in f"You asked: {question}".split():
yield "token", {"text": word + " "}
await asyncio.sleep(0.01)
yield "done", {"ok": True}
def sse(event, data):
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def chat(request):
given = request.headers.get("authorization", "").encode()
if not TOKEN or not hmac.compare_digest(given, f"Bearer {TOKEN}".encode()):
return JSONResponse({"error": "unauthorized"}, 401)
body = b""
async for chunk in request.stream():
body += chunk
if len(body) > MAX_BODY:
return JSONResponse({"error": "request too large"}, 413)
try:
question = str(json.loads(body)["question"])
except (ValueError, KeyError, TypeError):
return JSONResponse({"error": "send JSON with a question"}, 400)
if running.locked():
return JSONResponse({"error": "busy"}, 429, headers={"Retry-After": "2"})
async def stream():
async with running: # released even if the client leaves
try:
async with asyncio.timeout(30):
async for event, data in agent_events(question):
yield sse(event, data)
except TimeoutError:
yield sse("error", {"reason": "time limit"})
return StreamingResponse(stream(), media_type="text/event-stream",
headers={"Cache-Control": "no-store",
"X-Accel-Buffering": "no"})
async def health(request):
return JSONResponse({"alive": True})
async def ready(request):
return JSONResponse({"ready": bool(TOKEN)}, 200 if TOKEN else 503)
app = Starlette(routes=[Route("/chat", chat, methods=["POST"]),
Route("/healthz", health), Route("/readyz", ready)])
| Protection | Behavior |
|---|---|
| Token check | 401 without the right bearer token; refuses everything if no token is configured |
| Body limit | 413 above 4,096 bytes, counted while reading |
| Input check | 400 unless JSON with a question |
| Concurrency | 429 when all four slots are busy |
| Time limit | Stream ends with an error event after 30 seconds |
| Health | /healthz: process alive. /readyz: configured to serve |
One shared token identifies nobody; use the per-user checks from Lab: Least Privilege, Authentication and RBAC. The busy check runs just before the stream takes a slot, so some requests could in principle pass it and then wait. A real service also needs rate limits per user and a total budget.
What travels over the connection
Each message is a few lines of text followed by a blank line:
event: step
data: {"name": "lookup", "state": "started"}
event: token
data: {"text": "You "}
The status code is sent before the first event, so a failure that happens mid-stream cannot change it. Report it as an error event, and make the client treat a stream that ends without done as failed. The browser's built-in EventSource only sends GET requests and cannot set an authorization header, so a web client for this endpoint reads the response of a normal request as a stream.
Send step names that help a user, not raw tool arguments or internal reasoning. Everything in the stream can be seen by the caller.
Smoke test
A smoke test quickly checks that the main paths work. Save as smoke.py and run python smoke.py:
"""Smoke test a running service. Without an address it starts a local copy."""
import os
import secrets
import socket
import subprocess
import sys
import time
import httpx
def check(base, token):
auth = {"Authorization": f"Bearer {token}"}
with httpx.Client(base_url=base, timeout=10, trust_env=False) as http:
print("healthz ", http.get("/healthz").status_code)
print("readyz ", http.get("/readyz").status_code)
print("no token ", http.post("/chat", json={"question": "hi"}).status_code)
print("bad body ", http.post("/chat", content=b"x", headers=auth).status_code)
print("too large ", http.post("/chat", content=b"x" * 9000,
headers=auth).status_code)
events = []
with http.stream("POST", "/chat", headers=auth,
json={"question": "where is order A-1"}) as reply:
print("stream ", reply.status_code,
reply.headers["content-type"].split(";")[0])
for line in reply.iter_lines():
if line.startswith("event: "):
events.append(line[7:])
elif line.startswith("data: ") and events[-1] != "token":
print(" ", events[-1], line[6:])
print("token events ", events.count("token"), "| last event:", events[-1])
def main():
if len(sys.argv) > 1:
return check(sys.argv[1], os.environ["API_TOKEN"])
token = secrets.token_urlsafe(24)
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
server = subprocess.Popen(
[sys.executable, "-B", "-m", "uvicorn", "app:app", "--port", str(port),
"--log-level", "error"], env={**os.environ, "API_TOKEN": token})
base = f"http://127.0.0.1:{port}"
try:
for _ in range(100):
try:
httpx.get(base + "/healthz", trust_env=False)
break
except httpx.TransportError:
time.sleep(0.1)
check(base, token)
finally:
server.terminate()
server.wait(timeout=10)
if __name__ == "__main__":
main()
healthz 200
readyz 200
no token 401
bad body 400
too large 413
stream 200 text/event-stream
step {"name": "lookup", "state": "started"}
step {"name": "lookup", "state": "finished"}
done {"ok": true}
token events 6 | last event: done
Note that the test checks refusals as well as success. The same script can test a running container or deployment: set API_TOKEN and pass the address.
Package it
requirements.txt:
starlette==1.7.0
uvicorn==0.54.0
Dockerfile:
ARG BASE=python:3.13-slim
FROM ${BASE}
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
USER 10001:10001
EXPOSE 8000
CMD ["python", "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--timeout-graceful-shutdown", "25"]
.dockerignore, which starts by excluding everything so that keys and local files cannot slip in:
*
!app.py
!requirements.txt
Build, run with restrictions, and test. These commands use a bash shell:
docker build -t agent-api:0.1.0 .
export API_TOKEN=$(python -c "import secrets; print(secrets.token_urlsafe(24))")
docker run -d --name agent-api -p 127.0.0.1:8000:8000 -e API_TOKEN \
--read-only --cap-drop ALL --security-opt no-new-privileges --memory 256m \
agent-api:0.1.0
python smoke.py http://127.0.0.1:8000
docker exec agent-api id
docker stop agent-api && docker rm agent-api
With the stand-in base described above, the smoke test passed against the container, the process ran as user 10001, writing to the application folder failed because the file system was read-only, and the container stopped in under a second. Check the same four things on your machine.
| Image practice | Why |
|---|---|
| Small official base, pinned by digest for releases | Repeatable and less to patch |
| Pin dependencies, ideally with hashes | Same packages every build; indirect ones matter too |
| Non-root user | Limits damage after a break-in |
| No secrets in the image | Anyone with the image could read them |
| Scan and rebuild regularly | New weaknesses appear in old images |
Describe the deployment
Save as k8s.yaml:
apiVersion: apps/v1
kind: Deployment
metadata: {name: agent-api, labels: {app: agent-api}}
spec:
replicas: 2
strategy: {rollingUpdate: {maxUnavailable: 0, maxSurge: 1}}
selector: {matchLabels: {app: agent-api}}
template:
metadata: {labels: {app: agent-api}}
spec:
automountServiceAccountToken: false
terminationGracePeriodSeconds: 40
securityContext:
runAsNonRoot: true
runAsUser: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: api
image: registry.example.com/agent-api:0.1.0 # replace with yours
ports: [{name: http, containerPort: 8000}]
env:
- name: API_TOKEN
valueFrom: {secretKeyRef: {name: agent-api, key: token}}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: [ALL]}
resources:
requests: {cpu: 100m, memory: 128Mi}
limits: {memory: 256Mi}
readinessProbe: {httpGet: {path: /readyz, port: http}, periodSeconds: 5}
livenessProbe: {httpGet: {path: /healthz, port: http}, periodSeconds: 10}
---
apiVersion: v1
kind: Service
metadata: {name: agent-api}
spec:
selector: {app: agent-api}
ports: [{port: 80, targetPort: http}]
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: {name: agent-api}
spec:
minAvailable: 1
selector: {matchLabels: {app: agent-api}}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: agent-api}
spec:
podSelector: {matchLabels: {app: agent-api}}
policyTypes: [Ingress, Egress]
ingress:
- from: [{podSelector: {matchLabels: {role: gateway}}}]
ports: [{port: 8000}]
egress: [] # the lab agent calls nothing; add DNS and your model API
Save as validate.py and run it:
"""Check manifests against the Kubernetes schemas, then check our own rules."""
import yaml
import kubernetes_validate # pip install kubernetes-validate
VERSION = "1.37.0"
documents = list(yaml.safe_load_all(open("k8s.yaml", encoding="utf-8")))
for doc in documents:
kubernetes_validate.validate(doc, VERSION, strict=True)
print(f"schema ok {doc['kind']:<20} (Kubernetes {VERSION})")
pod = documents[0]["spec"]["template"]["spec"]
box = pod["containers"][0]
rules = {
"runs as non-root": pod["securityContext"].get("runAsNonRoot") is True,
"read-only root filesystem": box["securityContext"].get("readOnlyRootFilesystem"),
"no privilege escalation":
box["securityContext"].get("allowPrivilegeEscalation") is False,
"memory limit set": "memory" in box["resources"]["limits"],
"readiness probe set": "readinessProbe" in box,
"image has a fixed tag": not box["image"].endswith(":latest") and ":" in box["image"],
"secret not written inline": all("value" not in e for e in box["env"]),
}
for rule, ok in rules.items():
print(f"{'ok ' if ok else 'FAIL'} {rule}")
schema ok Deployment (Kubernetes 1.37.0)
schema ok Service (Kubernetes 1.37.0)
schema ok PodDisruptionBudget (Kubernetes 1.37.0)
schema ok NetworkPolicy (Kubernetes 1.37.0)
ok runs as non-root
ok read-only root filesystem
ok no privilege escalation
ok memory limit set
ok readiness probe set
ok image has a fixed tag
ok secret not written inline
A schema check proves the fields are valid, not that the deployment works. The script prints failures without stopping a pipeline; add a non-zero exit before relying on it.
What the settings do
| Setting | Effect |
|---|---|
maxUnavailable: 0 | A rollout adds a ready copy before removing an old one |
readinessProbe | Traffic only reaches copies that report ready |
livenessProbe | Restarts a stuck process; keep it independent of outside services |
terminationGracePeriodSeconds | Time to finish streams, longer than the server's 25-second wait |
PodDisruptionBudget | Keeps one copy during planned disruption |
NetworkPolicy | Only pods labeled as gateway may connect; nothing may leave |
Network policies need a network plugin that enforces them. Without one they have no effect, so test that a blocked connection really fails. The gateway rule matches pods in the same namespace.
Try it on a test cluster
kubectl create namespace agent-lab
kubectl -n agent-lab create secret generic agent-api --from-literal=token="$API_TOKEN"
kubectl -n agent-lab apply -f k8s.yaml
kubectl -n agent-lab rollout status deployment/agent-api
kubectl -n agent-lab port-forward service/agent-api 8000:80
python smoke.py http://127.0.0.1:8000 # second terminal
kubectl -n agent-lab rollout undo deployment/agent-api # after a second release
kubectl delete namespace agent-lab
These commands were not run. Replace the example image name with one your cluster can pull. Use a cluster created for learning, never a shared production one. Port forwarding does not test the network policy.
Estimate capacity before you choose numbers
An agent service spends most of its time waiting for models and tools. A rough first estimate for requests in progress is the arrival rate multiplied by the average duration.
arrivals per second: 2
average seconds per request: 6
requests in progress: 2 x 6 = 12
slots per copy: 4
copies needed: 12 / 4 = 3, plus room for peaks and one copy failing
These figures are an example, not a measurement. The lab manifest, with two copies of four slots, would refuse work at this load. Your model provider's rate limits may be reached before your own, so adding copies is not always the answer. Load test with a stand-in model first, then confirm with a small real test and a spending cap. See Latency, Load Testing and Capacity Planning.
Troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
| Pod never becomes ready | Secret missing or token empty | kubectl describe pod and events |
| Image cannot be pulled | Example image name or missing access | Image name and registry permissions |
| Repeated restarts | Crash, memory limit or failing liveness | Previous container logs |
| Events arrive all at once | A proxy buffers the response | Compare direct and gateway requests |
| Connection times out inside cluster | Network policy blocks the caller | Caller labels and namespace |
| Model calls fail after you add them | Outbound traffic is denied | Allow DNS and the model address |
| Streams cut during release | Shutdown time too short | Grace period and server wait |
The lab has not run on a cluster, so treat this table as a starting checklist rather than observed results.
Release with a way back
Version the prompt, model name, tool definitions and policy together with the code. Rolling back the image does not undo a changed database, a sent message or a provider's model change. See CI/CD, Infrastructure as Code and Safe Releases.
Capstone brief
Build one useful, narrow agent and ship it to a test environment. Choose a task with a checkable result, such as drafting replies to a set of sample support tickets.
| Requirement | Evidence | Lab |
|---|---|---|
| Narrow tools and stated limits | Tool list and limits | Starter Templates, Runbooks and Checklists |
| Standard connections where useful | Protocol tests | Lab: MCP Server and A2A Agent |
| Evaluation gate | Report with baseline | Lab: Evaluation Harness and Tracing |
| Identity and permissions | Refusal matrix and threat model | Lab: Least Privilege, Authentication and RBAC |
| Running service | Smoke test against the deployment | This lab |
| Operations | Runbook and rollback rehearsal | This lab |
Production-ready review
Score each line as shown, partly or not shown, with a link to evidence. "We intend to" counts as not shown.
- A named owner and a stated purpose with limits
- Critical evaluation cases pass; failures are understood
- Consequential actions need confirmation and are logged
- Cost, time and step limits are enforced and alerted
- Traces find the cause of a failed request without exposing private data
- Rollback and the disable switch have been rehearsed
- Someone else deployed it using only your instructions
Suggested order of work
- Write the task, the limits and ten evaluation cases before any agent code.
- Build the tools with tests, then the agent loop with a scripted model.
- Add permissions and the refusal matrix.
- Connect a real model with a spending cap and run the evaluation repeatedly.
- Add the API, container and smoke test.
- Deploy to the test environment, rehearse rollback, and ask someone else to follow your instructions.
Keep each stage small enough to finish, and record what you left out.
Runbook template
Service, owner, contact:
What it does and must never do:
Where logs and traces are:
How to tell it is healthy:
Disable the agent or one tool:
Roll back:
Known failures: symptom, check, fix
Who decides to turn it back on:
Break it on purpose
- Start the service without
API_TOKENand predict what both health addresses return. - Make the agent sleep for longer than the time limit and watch the client.
- Close the client during a stream, then confirm later requests are still served.
- Send many requests at once to trigger the busy reply, and record what happened.
- In a copy of the folder, remove the read-only setting from the manifest and confirm the validator reports it.
Common mistakes
| Mistake | Better practice |
|---|---|
| Liveness check that calls the model | An outside failure should not restart every copy |
| A proxy that buffers the stream | Test streaming through the real gateway |
| Keeping conversation state in one copy's memory | Store state outside the process |
| Treating a valid manifest as working | Apply it to a test cluster and test |
| Rollback never rehearsed | Practice it before you need it |
Frequently asked questions
Do I need Kubernetes?
No. A managed container or serverless service is often simpler. Use Kubernetes when your organization already runs it or you need its control.
Why server-sent events instead of WebSockets?
They suit one-way progress over ordinary HTTP. Use a two-way connection when the client must send data during the response.
How should long tasks run?
Accept the task, return an identifier and process it with a durable worker or queue instead of holding one request open.
Is this service production ready?
No. It teaches the shape. Identity, rate limits, TLS, monitoring, state and a tested cluster are still needed.
References and further reading
- Starlette responses
- HTML standard: server-sent events
- Docker build best practices
- Kubernetes Deployments
- Kubernetes Pod Security Standards
- Kubernetes network policies
Next steps
Deploying Agents to Production
Design the wider system.
Docker and Kubernetes for Agents
Go further with container platforms.
Agentic AI Projects and Portfolio Ideas
Present your capstone.