Nginx Ingress Controller Kubernetes 404路由问题排查求助
问题排查与修复方案
问题根源
你的请求路径是HEAD /fibonacci/23 HTTP/1.1,但当前Ingress配置的path = "/"(Prefix类型)会把完整的/fibonacci/23直接转发给后端服务。而你端口转发时应该是直接请求/23才正常,说明后端服务只响应/23这类路径,对/fibonacci/23没有对应路由,因此返回404。
修复方法
修改Terraform的Ingress配置,添加路径重写注解并调整匹配规则:
resource "kubernetes_ingress_v1" "example" { wait_for_load_balancer = true metadata { name = "fibonacci" namespace = "ingress-nginx" annotations = { # 重写路径,将/fibonacci/xxx转为/xxx转发给后端 "nginx.ingress.kubernetes.io/rewrite-target" = "/$2" } } spec { ingress_class_name = "nginx" rule { http { path { # 匹配所有以/fibonacci开头的请求路径 path = "/fibonacci(/|$)(.*)" path_type = "Prefix" backend { service { name = "fibonacci-service" port { number = 80 } } } } } } } }
原理说明
nginx.ingress.kubernetes.io/rewrite-target: /$2:通过正则分组提取/fibonacci/23中的23,将转发路径重写为/23,匹配后端服务的路由规则- 路径规则
/fibonacci(/|$)(.*):覆盖/fibonacci、/fibonacci/、/fibonacci/23等所有以/fibonacci开头的请求场景
额外检查项
- 确认后端Pod的
app标签确实为fibonacci-hello-world,保证Service能正确关联到Pod - 执行
kubectl describe ingress fibonacci -n ingress-nginx,验证Ingress规则是否已正常同步 - 查看Nginx Ingress Controller的Pod日志,排查是否存在路由加载异常信息
内容的提问来源于stack exchange,提问作者mornindew
相关产品推荐
相关产品推荐

