Kubernetes 中如何定义 Deployment 和 Service 来暴露 TensorFlow Serving 服务?

解读

在国内互联网/金融/制造企业的生产面试中,这道题考察的是“把训练好的模型真正跑起来”的工程闭环能力。
面试官想确认三件事:

  1. 你是否理解 TensorFlow Serving(TF-Serving)的容器化启动参数与模型热加载机制;
  2. 你是否能把“无状态推理服务”正确映射到 Kubernetes 的 Deployment + Service 模型;
  3. 你是否具备可观测、可灰度、可限流的运维意识(readiness、resource limit、labels、SessionAffinity、Headless 等细节)。
    回答时切忌只贴 YAML,而要“先讲设计,再给最小可用 YAML,最后补高可用与灰度方案”,体现 15k~40k 区间工程师的“落地思维”。

知识点

  1. TF-Serving 容器入口
    – tensorflow/serving:latest-gpu 镜像的默认 CMD 为 tensorflow_model_server;关键启动参数:
    --model_base_path=/models/<model_name>
    --model_name=<model_name>
    --rest_api_port=8501
    --allow_version_labels_for_unavailable_models=true(实现热更新)
  2. 模型存储规范
    – 国内普遍用对象存储(OSS、COS、OBS)+ 本地 EmptyDir 缓存,或直接用 PVC 挂 CephFS;目录结构必须符合
    /models/<model_name>/123456/(版本号子目录)。
  3. Deployment 设计要点
    – 无状态,replicas≥2;
    – 使用 readinessProbe 访问 /v1/models/<model_name> 判断模型已加载;
    – GPU 场景需指定 nvidia.com/gpu: 1 并加 toleration;
    – 镜像拉取密钥 imagePullSecrets(阿里云 ACR、腾讯云 TCR 均需私有拉取)。
  4. Service 暴露策略
    – 集群内访问:ClusterIP + 8501 即可;
    – 公网/边缘节点:LoadBalancer(腾讯云 CLB、阿里云 SLB)或 Ingress-NGINX + HTTPS;
    – 高并发推荐 sessionAffinity: ClientIP 避免反复 warm-up;
    – 需要 gRPC 时额外暴露 8500,并注意 appProtocol: http2。
  5. 灰度与弹性
    – 通过双 Deployment(stable/canary)+ 同一 Service 标签选择器实现权重灰度;
    – HPA 指标选 tensorflow/serving:requests 自定义指标或 CPU 70%。

答案

下面给出可直接 kubectl apply -f 的最小可用 YAML,并逐行解释设计意图。假设:
– 模型名称 mnist;
– 镜像已推送到阿里云杭州 ACR;
– 使用 PVC 只读挂载模型;
– 需要集群内 + 公网同时暴露。

  1. 模型持久化 PVC(已提前建好,此处仅声明)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mnist-model-pvc
  namespace: tf-serving
spec:
  accessModes:
    - ReadOnlyMany
  storageClassName: alibabacloud-cnfs-nas
  resources:
    requests:
      storage: 5Gi
  1. Deployment:双副本、就绪探针、资源限制、节点亲和
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tf-serving-mnist
  namespace: tf-serving
  labels:
    app: tf-serving-mnist
spec:
  replicas: 2
  selector:
    matchLabels:
      app: tf-serving-mnist
  template:
    metadata:
      labels:
        app: tf-serving-mnist
        version: v1
    spec:
      imagePullSecrets:
      - name: acr-hangzhou-secret
      containers:
      - name: tensorflow-serving
        image: registry.cn-hangzhou.aliyuncs.com/yourrepo/tf-serving:2.15.0-gpu
        args:
        - --model_name=mnist
        - --model_base_path=/models/mnist
        - --rest_api_port=8501
        - --monitoring_config_file=/config/monitoring.config
        - --allow_version_labels_for_unavailable_models=true
        ports:
        - containerPort: 8501
          name: http-infer
        - containerPort: 8500
          name: grpc-infer
        readinessProbe:
          httpGet:
            path: /v1/models/mnist
            port: 8501
          initialDelaySeconds: 15
          periodSeconds: 5
        resources:
          requests:
            cpu: "500m"
            memory: "1Gi"
            nvidia.com/gpu: "1"
          limits:
            cpu: "2"
            memory: "4Gi"
            nvidia.com/gpu: "1"
        volumeMounts:
        - name: model-storage
          mountPath: /models/mnist
          readOnly: true
      volumes:
      - name: model-storage
        persistentVolumeClaim:
          claimName: mnist-model-pvc
          readOnly: true
  1. Service:同时暴露 ClusterIP 与 LoadBalancer,支持 gRPC 与 REST
apiVersion: v1
kind: Service
metadata:
  name: tf-serving-mnist-svc
  namespace: tf-serving
  annotations:
    service.beta.kubernetes.io/alibaba-cloud-loadbalancer-spec: "slb.s2.small"
    service.beta.kubernetes.io/alibaba-cloud-loadbalancer-address-type: "internet"
spec:
  type: LoadBalancer
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10800
  ports:
  - name: http-infer
    port: 8501
    targetPort: 8501
    protocol: TCP
  - name: grpc-infer
    port: 8500
    targetPort: 8500
    protocol: TCP
    appProtocol: http2
  selector:
    app: tf-serving-mnist
  1. 验证
kubectl apply -f pvc.yaml -f deployment.yaml -f service.yaml
kubectl -n tf-serving get svc tf-serving-mnist-svc
curl -X POST http://<EXTERNAL-IP>:8501/v1/models/mnist:predict \
  -d '{"instances": ...}'

拓展思考

  1. 零中断热更新
    使用 tensorflow_model_server --enable_model_warmup=true + OSS 事件触发脚本,在新版本目录 ready 后自动改软链,实现“目录级原子切换”,无需重建 Pod。
  2. 多模型合并部署
    对 GPU 资源紧张的场景,可在同一个容器内用 --model_config_file 加载多个模型,降低显存碎片;此时需把 readinessProbe 改为循环探测 /v1/models/<each_model>。
  3. 自动弹性与成本优化
    结合阿里云 ACK 的 virtual-kubelet + ECI,把夜间低峰期副本缩到 0,白天按 QPS 自动弹出;GPU 节点使用抢占式实例,降低 70% 成本。
  4. 安全合规
    – 公网入口必须走 Ingress-NGINX + WAF,关闭 8500 端口外网暴露;
    – 模型文件使用阿里云 KMS 加密,Pod 内通过 CSI 插件自动解密;
    – 开启 istio mTLS,实现跨微服务调用的全链路加密。
  5. 可观测
    在 Deployment 内挂 tensorflow/serving:monitoring 端口(8502),Prometheus 采集 tensorflow:core:graph_runs 等指标,结合 Grafana 模板做实时 P99 延迟监控;同时把 opencensus trace 接入 SkyWalking,实现请求级追踪。