K8s AI集群运维实战指南:从零搭建GPU推理服务
搭建K8s AI集群前需要准备什么
在开始之前,请确认你已经有一个可用的Kubernetes集群(版本 ≥ 1.20),并且集群所有节点都能联网。
AI集群的核心是GPU资源,因此你还需要:
- 一台或多台安装了NVIDIA GPU的服务器(如A100、V100、RTX 3090等)
- NVIDIA驱动(版本 ≥ 450,运行
nvidia-smi能正常输出) - 熟悉
kubectl基本命令(如果还没装,先通过curl -LO https://dl.k8s.io/release/v1.27.0/bin/linux/amd64/kubectl && chmod +x kubectl && sudo mv kubectl /usr/local/bin/安装)
提示:如果没有物理GPU,也可以在云上申请GPU实例,步骤类似。
部署AI推理服务的完整步骤
第一步:安装NVIDIA设备插件
集群本身不识别GPU,需要安装 nvidia-device-plugin 才能让Pod请求GPU。
执行:
kubectl create -f https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v0.15.0/nvidia-device-plugin.yml
验证插件是否运行:
kubectl get pods -n kube-system | grep nvidia
如果看到 nvidia-device-plugin-daemonset-xxxxx 状态为 Running,说明安装成功。
第二步:创建测试Pod验证GPU可调度
写一个简单的YAML文件 gpu-test.yaml:
apiVersion: v1
kind: Pod
metadata:
name: gpu-test
spec:
containers:
- name: cuda-container
image: nvidia/cuda:12.2.0-base-ubuntu22.04
command: ["nvidia-smi"]
resources:
limits:
nvidia.com/gpu: 1
运行并查看日志:
kubectl apply -f gpu-test.yaml
kubectl logs gpu-test
如果输出GPU信息,说明调度成功。
之后可以自行删除测试Pod。
第三步:部署一个真实的AI推理服务
以部署一个基于TensorFlow Serving的模型为例。
先创建命名空间:
kubectl create namespace ai-inference
再写一个Deployment tf-serving.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: resnet50-serving
namespace: ai-inference
spec:
replicas: 2
selector:
matchLabels:
app: resnet50
template:
metadata:
labels:
app: resnet50
spec:
containers:
- name: tf-serving
image: tensorflow/serving:2.13.0-gpu
ports:
- containerPort: 8501
env:
- name: MODEL_NAME
value: resnet50
resources:
limits:
nvidia.com/gpu: 1
volumeMounts:
- name: model-storage
mountPath: /models/resnet50
volumes:
- name: model-storage
hostPath:
path: /data/models/resnet50
type: Directory
然后创建Service暴露访问入口:
kubectl expose deployment resnet50-serving --type=LoadBalancer --port=8501 -n ai-inference
注意:这里假设模型文件已经放在每个节点的 /data/models/resnet50 下。你也可以使用PV/PVC持久化。
常见配置陷阱与解决方法
问题1:Pod一直Pending,原因是GPU资源不足
检查节点GPU是否被占用:
kubectl describe node | grep -A5 "Capacity"
如果 nvidia.com/gpu 为0,说明设备插件未生效,重新安装或检查驱动。
问题2:Pod启动后立即CrashLoopBackOff
- 检查容器镜像是否支持GPU(如
tensorflow/serving:latest是CPU版本,需用...-gpu)。 - 确认
nvidia-smi在容器内能运行,或查看Pod日志定位错误。
问题3:多副本调度到同一节点导致性能瓶颈
使用 podAntiAffinity 让Pod尽量分散到不同GPU节点,配置示例:
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- resnet50
topologyKey: "kubernetes.io/hostname"
如何验证AI集群正常运行
部署完成后,用客户端发送一个推理请求:
curl -X POST http://:8501/v1/models/resnet50:predict -d '{"instances": [[...]]}'
返回JSON格式的预测结果,说明服务正常。
同时观察服务响应时间和GPU利用率,如果利用率偏低,可以适当增加并发请求测试性能。
另外,建议定期执行以下监控检查:
kubectl top pods -n ai-inference查看资源使用- 使用Prometheus+GPU Exporter采集GPU指标(可选)
- 检查
kubectl events -n ai-inference是否有异常事件
如果你正在处理K8s AI集群运维,建议先按本文步骤完整执行,再根据自己的环境做微调;
遇到异常时优先回看避坑和高频问题部分。