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

Kubernetes部署FastAPI时openapi.json 404错误求助

解决FastAPI部署在Kubernetes中OpenAPI文档路径404问题

问题分析

你的FastAPI应用通过https://api-gateway.example.com/myapp暴露,但OpenAPI文档尝试请求不带前缀的https://api-gateway.example.com/api/v1/openapi.json,本质是FastAPI没有正确识别自身的挂载路径前缀,导致生成的OpenAPI文档URL缺失/myapp。

常见解决方案

1. 同步配置FastAPI与Uvicorn的路径前缀

在main.py中创建FastAPI实例时指定root_path:

from fastapi import FastAPI

# 直接指定网关挂载的前缀
app = FastAPI(root_path="/myapp")

@app.get("/api/v1/test")
async def test():
    return {"message": "test"}

同时在Dockerfile的启动命令中添加--root-path参数,确保Uvicorn也识别该前缀:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY main.py .

# 添加--root-path参数匹配网关前缀
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--root-path", "/myapp"]

2. 通过Ingress自动传递前缀(推荐,无需硬编码)

如果使用NGINX Ingress,可通过配置注解让网关传递X-Forwarded-Prefix头,FastAPI会自动识别该值作为root_path:

Ingress配置示例:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    # 向FastAPI传递挂载前缀
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header X-Forwarded-Prefix /myapp;
spec:
  rules:
  - host: api-gateway.example.com
    http:
      paths:
      - path: /myapp(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 8000

此时main.py只需开启自动识别前缀的配置:

from fastapi import FastAPI

# 让OpenAPI文档自动使用识别到的root_path
app = FastAPI(root_path_in_servers=True)

3. 手动指定OpenAPI服务器地址

如果上述方法无效,可直接强制FastAPI的OpenAPI文档使用带前缀的路径:

from fastapi import FastAPI

app = FastAPI(
    servers=[
        {"url": "/myapp", "description": "API Gateway挂载前缀"}
    ]
)

验证方式

部署完成后访问https://api-gateway.example.com/myapp/docs,打开浏览器开发者工具,查看OpenAPI JSON的请求地址是否变为https://api-gateway.example.com/myapp/api/v1/openapi.json,若是则配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:42:44