Docker 与 K8s:AI 服务的容器化底座
容器不是「轻量虚拟机」,而是三件东西的组合:namespace 隔离视图、cgroups 限制资源、联合文件系统分层复用。K8s 在此之上做调度与自愈。本节不装 docker/kind,用可运行的 Python 把这三层的关键算术算清楚:分层去重能省多少、内存 limit 何时触发 OOMKill、requests/limits 如何决定 QoS、bin-packing 调度怎么把节点塞满。
1. 分层与去重:镜像为什么能共享
每个镜像层是内容寻址的(digest = 内容哈希),多个镜像引用同一层时磁盘只存一份。
import hashlib, json
def layer(name, files):
blob = json.dumps(files, sort_keys=True).encode()
return {"name": name, "digest": hashlib.sha256(blob).hexdigest()[:12],
"size_mb": sum(f["size"] for f in files)}
base = layer("ubuntu:22.04", [{"path": "/bin/bash", "size": 120}, {"path": "/lib/libc.so", "size": 2000}])
cuda = layer("cuda-runtime", [{"path": "/usr/local/cuda/libcudart.so", "size": 900}])
torch = layer("torch", [{"path": "/site-packages/torch/libtorch.so", "size": 1400}])
img_a = [base, cuda, torch, layer("app:v1", [{"path": "/app/main.py", "size": 5}])]
img_b = [base, cuda, torch, layer("app:v2", [{"path": "/app/main.py", "size": 6}])]
sizes = [sum(l["size_mb"] for l in img_a), sum(l["size_mb"] for l in img_b)]
naive_total = sum(sizes)
unique = {l["digest"]: l for img in (img_a, img_b) for l in img}
dedup_total = sum(l["size_mb"] for l in unique.values())
print(f"镜像 A 逻辑大小 {sizes[0]} MB,B 逻辑大小 {sizes[1]} MB")
print(f"不去重:{naive_total} MB;内容寻址去重后:{dedup_total} MB(省 {1 - dedup_total/naive_total:.1%})")
print(f"\n被共享的层: {[l['name'] for l in img_a[:3]]}")
print("实践含义:把『不常变的依赖』放前面、『代码』放最后一层 —— 改代码只重建最后一层;")
print("pip install 与 COPY . 的顺序错了,每次构建都会重装几 GB 依赖。")
# cgroups:内存 limit 与 OOMKill 判定
class Pod:
def __init__(self, name, req_mem, lim_mem, req_cpu=0.0):
self.name, self.req_mem, self.lim_mem, self.req_cpu = name, req_mem, lim_mem, req_cpu
def qos(p):
return "Guaranteed" if p.req_mem == p.lim_mem and p.lim_mem > 0 else ("Burstable" if p.req_mem > 0 else "BestEffort")
def oom(p, working_set):
"""cgroup v2 memory.max:超过就 OOMKill,没有 swap 兜底"""
return working_set > p.lim_mem
pods = [Pod("llm-server", 8000, 8000, 4), Pod("embedder", 2000, 4000, 2), Pod("batch-job", 0, 6000, 1)]
print(f"{'pod':<12}{'req':<8}{'limit':<8}{'QoS':<12}{'工作集':<8}{'结果'}")
print("-" * 58)
for p, ws in zip(pods, [7800, 3800, 5900]):
print(f"{p.name:<12}{p.req_mem:<8}{p.lim_mem:<8}{qos(p):<12}{ws:<8}{'OOMKilled' if oom(p, ws) else 'running'}")
print("\n同一组数字,batch-job 的 5900 MB 工作集没超 6000 的 limit —— 但它随时可能被驱逐:")
print("BestEffort/Burstable 在节点压力下先被杀;只有 Guaranteed(req==limit)有稳定保障。")
print("给 LLM 服务设 limit == request,是让它别被邻居挤死的常规做法。")
# K8s 调度:requests 决定能否上岸,bin-packing 决定装多少
import numpy as np
rng = np.random.default_rng(1)
nodes = [(32, 128)] * 3 # (cpu 核, 内存 GB)
pods = [(int(rng.integers(2, 14)), int(rng.integers(4, 60))) for _ in range(16)]
def schedule(pods, nodes, key):
remain = [list(n) for n in nodes]
placed = []
for idx, (c, m) in enumerate(pods):
cands = [i for i, (rc, rm) in enumerate(remain) if rc >= c and rm >= m]
if not cands:
continue
i = key(cands, remain, c, m)
remain[i][0] -= c; remain[i][1] -= m
placed.append(idx)
return len(placed), remain
first = schedule(pods, nodes, lambda cands, r, c, m: cands[0])
best = schedule(pods, nodes, lambda cands, r, c, m: max(cands, key=lambda i: (r[i][1] - m) * (r[i][0] - c)))
print(f"共 {len(pods)} 个 pod,3 节点各 32c/128G(总供给 96c/384G)")
print(f"first-fit 调度成功 {first[0]} 个,剩余 {first[1]}")
print(f"best-fit 调度成功 {best[0]} 个,剩余 {best[1]}")
print(f"\nPod 总需求 cpu={sum(p[0] for p in pods)}c, mem={sum(p[1] for p in pods)}G —— 需求总量已超供给,注定有 pod Pending")
print("即便总量够,碎片也会让 pod 无处落;调度策略的好坏就差在这里(本例 best-fit 多塞进 1 个)。")
print("\nYAML 里的三件套:resources.requests(调度依据)、resources.limits(cgroup 上限)、")
print("nodeSelector/affinity(GPU 机型必须绑,否则 GPU pod 会被调度到 CPU 节点然后永远 Pending)。")
2. 一份能用的 Deployment
AI 服务的 manifest 有四个必填项:资源、探针、拉取策略、优雅退出。
| 字段 | 作用 | AI 服务常见取值 |
|---|---|---|
requests/limits | 调度 + cgroup | GPU: nvidia.com/gpu: 1,内存 req==limit |
readinessProbe | 就绪才接流量 | 模型加载完再 /healthz 返回 200,initialDelaySeconds 给 60s+ |
livenessProbe | 卡死重启 | 不要用「模型推理耗时」做超时,容易误杀 |
terminationGracePeriodSeconds | 优雅退出 | 大于最长请求时长,配合 preStop 摘流量 |
# 把上面的约束写成 manifest,并做最小校验
import yaml
manifest = {
"apiVersion": "apps/v1", "kind": "Deployment",
"metadata": {"name": "llm-server", "labels": {"app": "llm-server"}},
"spec": {
"replicas": 2,
"selector": {"matchLabels": {"app": "llm-server"}},
"template": {
"metadata": {"labels": {"app": "llm-server"}},
"spec": {
"terminationGracePeriodSeconds": 120,
"containers": [{
"name": "server",
"image": "registry.example.com/llm-server:v1.2",
"imagePullPolicy": "IfNotPresent",
"ports": [{"containerPort": 8000}],
"resources": {
"requests": {"cpu": "8", "memory": "32Gi", "nvidia.com/gpu": 1},
"limits": {"cpu": "8", "memory": "32Gi", "nvidia.com/gpu": 1},
},
"readinessProbe": {"httpGet": {"path": "/healthz", "port": 8000},
"initialDelaySeconds": 90, "periodSeconds": 10},
"livenessProbe": {"httpGet": {"path": "/livez", "port": 8000},
"initialDelaySeconds": 120, "periodSeconds": 30,
"failureThreshold": 3},
}],
},
},
},
}
text = yaml.safe_dump(manifest, allow_unicode=True, sort_keys=False)
print(text[:40].replace("\n", " ") + " ... (共 %d 行)" % len(text.splitlines()))
def lint(m):
errs = []
spec = m["spec"]["template"]["spec"]
c = spec["containers"][0]
res = c["resources"]
if res["requests"] != res["limits"]:
errs.append("requests != limits → QoS 不是 Guaranteed")
if not any(f == "readinessProbe" for f in c):
errs.append("缺 readinessProbe:模型没加载完就接流量")
if c.get("imagePullPolicy") == "Always" and ":latest" not in c["image"]:
errs.append("固定 tag 却写 Always,会白拉镜像")
if spec.get("terminationGracePeriodSeconds", 30) < 60:
errs.append("优雅退出时间过短:长请求会被硬杀")
if "nvidia.com/gpu" in res["requests"] and "nodeSelector" not in spec:
errs.append("GPU 未绑定 nodeSelector:可能被调度到 CPU 节点")
return errs
errs = lint(manifest)
print("lint 结果:", errs if errs else "全部通过(除 nodeSelector —— 本示例假设集群只有 GPU 机型)")
print("\n上线前 checklist:镜像 tag 固定 → resources req==limit → 探针分健康/就绪 → 优雅退出 > 最长请求 → GPU 亲和性。")
站内关联与参考来源
- 延伸:20 · 部署、35 · vLLM/SGLang
- 融合参考:
chunhuizhang/docker_k8s/*.ipynb、chunhuizhang/mlops/{dockerfile, k8s_manifest}.ipynb。