在Nginx-ingress-controller的K8s环境中,能否同时用Ingress LB IP和域名访问应用?
问题描述
在部署了Nginx-ingress-controller的Kubernetes环境中,我配置了一个使用虚拟域名example.local的Ingress资源,通过该域名可正常访问后端应用,但使用对应的Ingress负载均衡器IP(192.168.122.241)访问时却返回404页面未找到。请问是否可以同时使用这两种方式访问应用?
以下是kubectl describe ingress的输出信息:
~]# kubectl describe ingress Name: hello-world-ing Labels: <none> Namespace: default Address: 192.168.122.241 Ingress Class: <none> Default backend: <default> Rules: Host Path Backends ---- ---- -------- example.local / apache:80 (10.32.0.4:80) Annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Sync 2m8s (x10 over 83m) nginx-ingress-controller Scheduled for sync
解答
可以同时通过域名和负载均衡器IP访问应用,当前直接用IP访问返回404的原因是:你的Ingress规则仅匹配Host头为example.local的请求,而直接访问IP时,请求的Host头是IP本身(或为空),没有匹配的Ingress规则,因此会路由到默认后端,但你的Ingress默认后端是<default>(未配置实际服务),所以返回404。
解决方法有两种:
方法1:修改Ingress添加默认路由规则
在Ingress的rules中添加一条不指定host的规则,这样所有未匹配到特定Host的请求(包括直接用IP访问的请求)都会被路由到后端服务。修改后的Ingress YAML示例如下:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: hello-world-ing annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: # 保留原有的域名匹配规则 - host: example.local http: paths: - path: / pathType: Prefix backend: service: name: apache port: number: 80 # 添加默认路由,匹配无Host头或IP访问的请求 - http: paths: - path: / pathType: Prefix backend: service: name: apache port: number: 80
应用修改后的Ingress:
kubectl apply -f your-ingress-file.yaml
等待Ingress Controller同步规则后,直接访问192.168.122.241就能正常访问后端应用了。
方法2:访问IP时手动指定Host头(临时测试用)
如果只是临时测试,不想修改Ingress,可以通过curl等工具手动指定Host头来模拟域名访问:
curl -H "Host: example.local" 192.168.122.241
这种方式仅适用于单次测试,无法作为长期访问方案。
内容的提问来源于stack exchange,提问作者Chandan
相关产品推荐
相关产品推荐

