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

如何在单域名下为React应用+Express配置K8s Ingress?

Hey there! Let's get your ingress routing sorted for your React frontend and Node backend on GKE. You're aiming to route all /api/* traffic to be-service and everything else to fe-service via a single domain—here's a solid solution:

Correct Ingress Configuration

First, use this updated YAML tailored for GKE's native GCE Ingress controller:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    kubernetes.io/ingress.class: "gce"
    # Optional: Uncomment if you want HTTPS with a GCP managed certificate
    # networking.gke.io/managed-certificates: your-certificate-name
spec:
  rules:
  - host: your-custom-domain.com  # Replace with your actual domain
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: be-service
            port:
              number: 80  # Swap with your backend service's actual port (e.g., 3000)
      - path: /
        pathType: Prefix
        backend:
          service:
            name: fe-service
            port:
              number: 80  # Swap with your frontend service's actual port (e.g., 8080)

Key Details to Note:

  • Ingress Class Annotation: The kubernetes.io/ingress.class: "gce" line ensures GKE uses its native ingress controller, which avoids conflicts with third-party controllers like NGINX Ingress.
  • Path Order: Always list more specific paths (like /api) first. GKE evaluates rules top-to-bottom, so if / was placed first, it would catch all traffic before /api gets matched.
  • PathType: Prefix means any request starting with /api (e.g., /api/users, /api/orders) routes to your backend, while / catches every other path (root, /about, /dashboard, etc.) for the frontend.

Testing the Setup

Verify the routing works with curl by specifying the correct Host header (since your ingress is tied to a domain):

# Test backend routing (replace <your-ingress-external-ip> and domain with your values)
curl http://<your-ingress-external-ip>/api/health --header "Host: your-custom-domain.com"

# Test frontend routing
curl http://<your-ingress-external-ip>/ --header "Host: your-custom-domain.com"

Fixing SPA Routing Issues (If They Pop Up)

If you get 404 errors when refreshing React routes (like /dashboard), your frontend's web server (e.g., Nginx) needs to redirect all non-asset requests to index.html. Add this to your frontend's Nginx config:

server {
  listen 80;
  root /usr/share/nginx/html;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

This ensures client-side routes are handled by React Router instead of returning a 404 when users refresh the page.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:48:38