You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

K8s环境下调用Weather API遇308重定向及500错误的解决求助

问题排查与解决方案

一、308重定向问题修复

308永久重定向大概率和Nginx Ingress的路径匹配规则相关,常见修复方式:

  • 调整Ingress路径与重定向注解:如果Ingress路径配置为/api,后端服务可能期望带末尾斜杠的路径,Nginx会自动触发重定向。修改Ingress配置,使用路径正则匹配并添加重定向注解:
    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: weather-ingress
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /$2
        # 若不需要强制HTTPS跳转,注释下方配置
        # nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    spec:
      rules:
      - http:
          paths:
          - path: /api(/|$)(.*)
            pathType: Prefix
            backend:
              service:
                name: weather-service
                port:
                  number: 80
    
  • 检查HTTPS强制跳转:如果Ingress开启了force-ssl-redirect,用curl访问HTTP协议会触发308跳转。可临时关闭该注解,或改用curl -L "https://localhost/api?latitude=52&longitude=5"跟随HTTPS重定向。

二、500内部错误排查

跳转后出现500,说明后端服务处理请求时异常,按以下方向排查:

  1. 查看后端Pod日志:执行kubectl logs <你的weather-pod名称>,定位具体报错:
    • 第三方Weather API密钥未正确注入(比如未通过ConfigMap/Secret配置)
    • 经纬度参数解析失败(比如代码未正确获取request.args中的参数)
    • 依赖库缺失(比如Docker镜像未安装requests或flask)
  2. 检查后端代码逻辑:
    • 确保main.py正确处理参数并捕获异常:
      from flask import Flask, request
      import weather
      
      app = Flask(__name__)
      
      @app.route('/api', methods=['GET'])
      def get_weather():
          lat = request.args.get('latitude')
          lon = request.args.get('longitude')
          if not lat or not lon:
              return "缺少经纬度参数", 400
          try:
              return weather.fetch_weather(lat, lon), 200
          except Exception as e:
              print(f"处理错误: {str(e)}")
              return "服务器内部错误", 500
      
      if __name__ == '__main__':
          app.run(host='0.0.0.0', port=5000)
      
    • 确保weather.py调用第三方API时处理HTTP异常:
      import requests
      
      def fetch_weather(lat, lon):
          api_key = "你的API密钥"  # 建议通过环境变量注入
          url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}"
          resp = requests.get(url)
          resp.raise_for_status()  # 触发HTTP状态码异常
          return resp.json()
      
  3. 验证Docker镜像完整性:确认Dockerfile安装了所有依赖:
    FROM python:3.9-slim
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    COPY main.py weather.py .
    CMD ["python", "main.py"]
    
    requirements.txt需包含:
    flask>=2.0
    requests>=2.25
    

三、验证步骤

  1. 应用修正后的Ingress配置:kubectl apply -f ingress.yaml
  2. 确认Pod状态正常:kubectl get pods
  3. 重新测试API:
    • 关闭强制HTTPS时:curl "localhost/api?latitude=52&longitude=5"
    • 开启强制HTTPS时:curl -L "https://localhost/api?latitude=52&longitude=5"

内容的提问来源于stack exchange,提问作者Gion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:10:15