我第一次在 Kubernetes 集群里配置 AI API 路由的时候,被各种 YAML 配置折磨了整整两天。ingress、service、deployment 这些概念绕来绕去,网关地址配错了导致请求全部超时,API Key 暴露在明文配置里差点酿成安全事故。今天我把这些血泪经验整理成这篇教程,手把手带你从零完成配置,文末还准备了排错清单保证你一次成功。

一、为什么要在 Kubernetes 里配置 AI API 网关?

当你的 AI 应用从单机部署升级到 Kubernetes 集群时,统一的 API 路由变得至关重要。通过 Ingress 控制器,你可以实现:请求的负载均衡、域名解析、自动 HTTPS 证书、以及对 AI 接口的访问控制。

如果你还没有 API Key,推荐使用 立即注册 HolySheep AI,这家平台的汇率是 ¥1=$1,相较官方 ¥7.3=$1 可以节省超过 85% 的成本,而且支持微信和支付宝充值,国内服务器延迟低于 50 毫秒,新用户还赠送免费额度。

二、环境准备清单

2.1 基础工具检查

在开始之前,请确保你的电脑上已经安装了以下工具(用文字模拟截图提示):

如果没有安装,推荐使用 kind 在本地快速创建集群(用文字模拟截图提示):

# 安装 kind(macOS 示例)
brew install kind

创建单节点集群

kind create cluster --name ai-api-cluster

确认集群状态

kubectl cluster-info

2.2 安装 Ingress 控制器

Kubernetes 默认不安装 Ingress 控制器,需要手动部署。我推荐使用 nginx-ingress(用文字模拟截图提示):

# 使用官方 yaml 部署 nginx-ingress
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.9.4/deploy/static/provider/cloud/deploy.yaml

等待 Pod 就绪

kubectl wait --namespace ingress-nginx \ --for=condition=ready pod \ --selector=app.kubernetes.io/component=controller \ --timeout=120s

确认安装成功

kubectl get pods -n ingress-nginx

三、部署你的第一个 AI API 应用

3.1 创建 API 代理 Deployment

我们先部署一个简单的代理服务,它负责将请求转发给 AI API。这里的核心是使用 HolySheep AI 作为后端服务,它的 GPT-4.1 价格是 $8/MTok、Claude Sonnet 4.5 是 $15/MTok、Gemini 2.5 Flash 仅 $2.50/MTok、DeepSeek V3.2 更是低至 $0.42/MTok,性价比非常突出。

# 创建 api-proxy namespace
kubectl create namespace ai-proxy

创建 configmap 存储配置

kubectl create configmap ai-config -n ai-proxy \ --from-literal=BASE_URL=https://api.holysheep.ai/v1 \ --from-literal=API_VERSION=2024-01-01

创建 api-proxy-deployment.yaml

cat > api-proxy-deployment.yaml << 'EOF' apiVersion: apps/v1 kind: Deployment metadata: name: ai-api-proxy namespace: ai-proxy spec: replicas: 2 selector: matchLabels: app: ai-proxy template: metadata: labels: app: ai-proxy spec: containers: - name: proxy image: nginx:alpine ports: - containerPort: 80 env: - name: API_KEY valueFrom: secretKeyRef: name: ai-secrets key: api-key volumeMounts: - name: config mountPath: /etc/nginx/conf.d volumes: - name: config configMap: name: nginx-config EOF kubectl apply -f api-proxy-deployment.yaml

3.2 创建 API Key 的 Secret

这里要特别注意:绝对不要把 API Key 硬编码在 YAML 文件里!必须使用 Kubernetes Secret。

# 创建包含 API Key 的 Secret
kubectl create secret generic ai-secrets -n ai-proxy \
  --from-literal=api-key=YOUR_HOLYSHEEP_API_KEY

验证 Secret 已创建(不会显示真实内容)

kubectl get secret ai-secrets -n ai-proxy

如果需要更新 Key

kubectl patch secret ai-secrets -n ai-proxy \ -p '{"stringData":{"api-key":"YOUR_NEW_API_KEY"}}'

3.3 创建 Service 暴露应用

# 创建 service.yaml
cat > service.yaml << 'EOF'
apiVersion: v1
kind: Service
metadata:
  name: ai-proxy-service
  namespace: ai-proxy
spec:
  selector:
    app: ai-proxy
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: ClusterIP
EOF

kubectl apply -f service.yaml

确认 Service 运行正常

kubectl get svc -n ai-proxy

四、配置 Ingress 路由规则

4.1 编写 Ingress 配置

这是整个教程最核心的部分。我们需要配置 Ingress 将外部请求路由到内部的 AI API 服务。

# 创建 ingress.yaml
cat > ingress.yaml << 'EOF'
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ai-api-ingress
  namespace: ai-proxy
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/proxy-body-size: "50m"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
    nginx.ingress.kubernetes.io/enable-cors: "true"
spec:
  ingressClassName: nginx
  rules:
  - host: ai-api.yourdomain.com
    http:
      paths:
      - path: /v1
        pathType: Prefix
        backend:
          service:
            name: ai-proxy-service
            port:
              number: 80
  tls:
  - hosts:
    - ai-api.yourdomain.com
    secretName: ai-api-tls
EOF

kubectl apply -f ingress.yaml

查看 Ingress 状态

kubectl get ingress -n ai-proxy

4.2 配置 HTTPS 证书(可选但强烈推荐)

如果你没有现成的证书,可以使用 cert-manager 自动申请 Let's Encrypt 免费证书。

# 安装 cert-manager
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.2/cert-manager.yaml

创建 ClusterIssuer(用于 Let's Encrypt)

cat > issuer.yaml << 'EOF' apiVersion: cert-manager.io/v1 kind: ClusterIssuer metadata: name: letsencrypt-prod spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: [email protected] privateKeySecretRef: name: letsencrypt-prod solvers: - http01: ingress: class: nginx EOF kubectl apply -f issuer.yaml

在 Ingress 中添加注解启用自动 HTTPS

kubectl annotate ingress ai-api-ingress -n ai-proxy \ cert-manager.io/cluster-issuer=letsencrypt-prod \ --overwrite

五、实战测试:验证 API 调用

5.1 本地端口转发测试

在配置 DNS 之前,我们先用端口转发方式测试一下(用文字模拟截图提示):

# 开启端口转发到本地
kubectl port-forward -n ai-proxy svc/ai-proxy-service 8080:80 &

测试请求(记得把 YOUR_HOLYSHEEP_API_KEY 换成你的真实 Key)

curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_HOLYSHEEP_API_KEY" \ -d '{ "model": "gpt-4.1", "messages": [{"role": "user", "content": "Hello!"}] }'

5.2 完整的前端应用示例

以下是一个完整的 Python 应用示例,直接对接我们配置的 Kubernetes Ingress:

# ai_client.py
import requests

class HolySheepAIClient:
    def __init__(self, api_key: str, base_url: str = "https://ai-api.yourdomain.com/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def chat(self, model: str, messages: list, temperature: float = 0.7):
        """发送聊天请求到 HolySheep AI"""
        endpoint = f"{self.base_url}/chat/completions"
        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature
        }
        response = requests.post(endpoint, json=payload, headers=self.headers)
        response.raise_for_status()
        return response.json()

使用示例

client = HolySheepAIClient(api_key="YOUR_HOLYSHEEP_API_KEY") result = client.chat( model="gpt-4.1", messages=[{"role": "user", "content": "用中文回答:什么是 Kubernetes Ingress?"}] ) print(result["choices"][0]["message"]["content"])

六、常见报错排查

6.1 错误一:502 Bad Gateway

这个错误通常意味着 Ingress Controller 无法连接到后端 Service。

# 排查步骤:

1. 检查后端 Pod 是否运行

kubectl get pods -n ai-proxy

2. 查看 Pod 日志

kubectl logs -n ai-proxy -l app=ai-proxy --tail=100

3. 检查 Service 是否正确选择 Pod

kubectl describe svc ai-proxy-service -n ai-proxy

4. 测试 Service 连通性

kubectl run test --rm -it --image=busybox --restart=Never -- wget -qO- http://ai-proxy-service.ai-proxy

6.2 错误二:403 Forbidden 或认证失败

API Key 认证失败通常由以下原因导致:

# 排查步骤:

1. 确认 Secret 存在且内容正确

kubectl get secret ai-secrets -n ai-proxy -o jsonpath='{.data.api-key}' | base64 -d

2. 检查 Secret 是否被正确挂载到 Pod

kubectl exec -n ai-proxy deploy/ai-api-proxy -- env | grep API_KEY

3. 验证 API Key 是否有效(直接调用 HolySheep API)

curl -X POST https://api.holysheep.ai/v1/chat/completions \ -H "Authorization: Bearer YOUR_HOLYSHEEP_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model":"gpt-4.1","messages":[{"role":"user","content":"test"}]}'

6.3 错误三:Ingress 资源无法创建

# 排查步骤:

1. 检查 Ingress Controller 是否正常

kubectl get pods -n ingress-nginx

2. 查看 Ingress 事件

kubectl describe ingress ai-api-ingress -n ai-proxy

3. 检查命名空间是否正确

kubectl get ingress --all-namespaces | grep ai-proxy

4. 确认 ingressClassName 是否匹配

kubectl get ingressclass

6.4 错误四:请求超时或响应缓慢

我第一次部署的时候就遇到了这个问题,从国内访问 API 延迟高达 3 秒。原因是我用的云服务器在海外,而且没有配置缓存。

# 排查步骤:

1. 测试网络延迟

ping ai-api.yourdomain.com

2. 检查 Ingress 配置的 timeout 参数

确保 annotation 中有:

nginx.ingress.kubernetes.io/proxy-read-timeout: "300"

nginx.ingress.kubernetes.io/proxy-send-timeout: "300"

3. 启用响应缓存减少 AI API 调用次数

kubectl annotate ingress ai-api-ingress -n ai-proxy \ nginx.ingress.kubernetes.io/proxy-cache-path=/tmp/nginx-cache levels=2:2 use_stale="+1" min_uses=3

七、生产环境最佳实践

八、总结

通过这篇文章,我们完成了从零搭建 Kubernetes Ingress 配置 AI API 网关的全流程。核心步骤包括:安装 Ingress 控制器、部署代理服务、配置路由规则、以及完善的安全和监控措施。

如果你还在寻找性价比高的 AI API 服务,立即注册 HolySheep AI 是明智之选。¥1=$1 的汇率相比官方节省超过 85%,支持微信和支付宝充值,国内直连延迟低于 50ms,新用户注册即送免费额度。主流模型价格透明:GPT-4.1 $8/MTok、Claude Sonnet 4.5 $15/MTok、Gemini 2.5 Flash $2.50/MTok、DeepSeek V3.2 $0.42/MTok。

有任何问题欢迎在评论区留言,我会尽力解答。祝你部署顺利!

👉 免费注册 HolySheep AI,获取首月赠额度