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

FastAPI部署AWS EKS集群遇Ambassador路径多斜杠致404问题

解决FastAPI在AWS EKS通过Ambassador部署时路径双斜杠导致的404问题

问题场景

在AWS EKS集群部署FastAPI应用后,外部访问端点返回404错误,服务日志显示请求路径被拼接为//ping,而非预期的/ping。集群内部直接测试FastAPI服务可正常响应,且相同K8s配置部署Flask应用无此异常。

相关代码与配置

FastAPI核心路由代码:

from fastapi import FastAPI, HTTPStatus

app = FastAPI()

@app.get("/ping")
async def ping():
    """Health check"""
    response = {
        "message": HTTPStatus.OK.phrase,
        "status-code": HTTPStatus.OK
    }
    return response

Ambassador Mapping配置片段:

apiVersion: getambassador.io/v2
kind: Mapping
metadata:
  name: fastapi-example
  namespace: gpu
spec:
  prefix: fastapi-example
  service: fastapi-example.gpu:8080

问题根源

FastAPI采用严格的路由匹配机制,不会自动归一化路径(如将//ping识别为/ping);而Flask会自动处理这类路径格式问题。当Ambassador的prefix配置不带末尾斜杠时,转发请求时会将前缀与原路径直接拼接,导致出现双斜杠路径,触发FastAPI的404错误。

解决方案

提供两种可行的修复方式:

方式1:给Ambassador的prefix添加末尾斜杠

修改Mapping的prefix字段,添加末尾斜杠,确保路径拼接时不会出现重复斜杠:

apiVersion: getambassador.io/v2
kind: Mapping
metadata:
  name: fastapi-example
  namespace: gpu
spec:
  prefix: fastapi-example/
  service: fastapi-example.gpu:8080

方式2:启用Ambassador的rewrite规则

保持prefix不变,添加rewrite: /配置,让Ambassador将前缀替换为根路径,保证转发路径格式正确:

apiVersion: getambassador.io/v2
kind: Mapping
metadata:
  name: fastapi-example
  namespace: gpu
spec:
  prefix: fastapi-example
  rewrite: /
  service: fastapi-example.gpu:8080

验证步骤

修改配置后,重新应用到集群:

kubectl apply -f <你的部署文件名>.yaml -n gpu

再次访问/fastapi-example/ping,此时服务日志应显示请求路径为/ping,FastAPI将正常返回200响应。

内容的提问来源于stack exchange,提问作者J.Sean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:58:07