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

GCP Cloud Run多容器部署下Nginx反向代理API调用异常排查

问题分析与解决方案

核心问题根源

前端代码中调用的https://127.0.0.1:8080/api/chat/指向用户本地机器的localhost,而非Cloud Run多容器实例内部的FastAPI sidecar服务。本地Docker环境中,前端与后端共享同一Docker网络,浏览器请求的是本地映射端口所以能连通;但Cloud Run场景下,前端代码在用户浏览器中运行,发起的请求无法触及容器内部的127.0.0.1。


具体解决方案

1. 修改前端API请求地址

将前端中硬编码的https://127.0.0.1:8080/api/替换为相对路径(/api/)或LB的静态IP地址(https://10.196.XXX.XX/api/):

  • 使用相对路径:前端请求会自动继承当前页面的域名/IP,无需额外配置域名
  • 使用LB地址:直接指向外部可访问的后端入口,适合跨域场景

2. 配置Nginx反向代理(容器内转发)

在Cloud Run的Nginx配置中添加反向代理规则,将前端的/api/*请求转发到容器内的FastAPI服务(多容器共享同一网络命名空间,可直接用localhost访问)。示例配置:

server {
    listen 8080;
    server_name _;

    # 托管React静态文件
    root /usr/share/nginx/html;
    index index.html;

    # 反向代理API请求到FastAPI sidecar
    location /api/ {
        proxy_pass http://localhost:8080/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # 处理CORS预请求
        add_header Access-Control-Allow-Origin "https://10.196.XXX.XX" always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
        
        if ($request_method = OPTIONS) {
            return 204;
        }
    }

    # SPA路由 fallback(React路由需要)
    location / {
        try_files $uri $uri/ /index.html;
    }
}

3. 调整Cloud Run服务配置

  • 在service.yml中,仅将Nginx容器的端口(如8080)设置为Cloud Run的对外暴露端口,FastAPI容器无需对外暴露端口(内部通过localhost访问即可):
spec:
  template:
    spec:
      containers:
      - name: nginx-frontend
        image: gcr.io/your-project/nginx-frontend
        ports:
        - containerPort: 8080
        volumeMounts:
        - name: nginx-config-secret
          mountPath: /etc/nginx/conf.d
      - name: fastapi-backend
        image: gcr.io/your-project/fastapi-backend
      volumes:
      - name: nginx-config-secret
        secret:
          secretName: nginx-config-secret

4. 验证容器内网络连通性

可通过Cloud Run的交互式shell进入Nginx容器,执行curl http://localhost:8080/api/chat/,确认能正常获取后端响应,排除容器间网络连通问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:10:12