配置Ingress NGINX访问Kubernetes Pod遇502 Bad Gateway错误求助
解决Kubernetes Ingress NGINX 502 Bad Gateway问题
问题背景
在Windows Docker Desktop的本地Kubernetes集群配置Ingress NGINX暴露微服务时,出现502 Bad Gateway错误,Ingress日志显示:
connect() failed (111: Connection refused)Service 'default/auth-cluster-ip' does not have any active Endpoint
已完成Ingress规则、Deployment/Service的YAML配置,更新了hosts文件,且直接端口转发Pod可正常访问,但Ingress无法连接后端服务。
配置文件参考
Ingress NGINX配置
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-service annotations: nginx.ingress.kubernetes.io/use-regex: "true" spec: ingressClassName: nginx rules: - host: instagram-clone.dev http: paths: - path: /v1/auth/?(.*) pathType: ImplementationSpecific backend: service: name: auth-cluster-ip port: number: 3000 - path: /v1/profile/?(.*) pathType: ImplementationSpecific backend: service: name: profile-cluster-ip port: number: 3000
Auth组件部署及服务
apiVersion: apps/v1 kind: Deployment metadata: name: auth-depl spec: replicas: 1 selector: matchLabels: app: auth template: metadata: labels: app: auth spec: containers: - name: auth image: instagram-clone/auth env: - name: JWT_SECRET valueFrom: secretKeyRef: name: jwt-secret key: JWT_SECRET --- apiVersion: v1 kind: Service metadata: name: auth-cluster-ip spec: selector: app: auth ports: - name: auth protocol: TCP port: 3000 targetPort: 3000
Node.js Auth服务代码片段
export const app = express(); app.use(json()); app.use("/", authRouter);
解决方案
1. 确认Service与Pod的Endpoint关联
- 执行命令查看Service的Endpoint状态:
若输出中kubectl get endpoints auth-cluster-ipENDPOINTS列为空,说明Service未匹配到Pod:- 检查Deployment的Pod标签
app: auth与Service的selector: app: auth是否完全一致(注意大小写、拼写) - 执行
kubectl get pods -l app=auth确认Pod是否处于Running状态,若Pod未就绪,查看日志排查启动问题:kubectl logs <auth-pod-name>
- 检查Deployment的Pod标签
2. 修正Node.js服务的监听地址
本地集群常见问题:若Node.js服务仅监听localhost,容器外部(包括Kubernetes Service)无法访问。
- 检查服务启动代码,确保监听地址为
0.0.0.0,示例:app.listen(3000, '0.0.0.0', () => { console.log('Auth service running on port 3000'); }); - 重新构建镜像并更新Deployment,验证Pod内服务可通过Pod IP访问:
kubectl exec <auth-pod-name> -- curl <pod-ip>:3000
3. 添加Ingress路径重写注解
当前Ingress将/v1/auth/xxx完整路径转发给服务,但服务路由以/开头,导致404进而引发Ingress 502错误。
- 修改Ingress的
metadata.annotations,添加路径重写规则:metadata: name: ingress-service annotations: nginx.ingress.kubernetes.io/use-regex: "true" nginx.ingress.kubernetes.io/rewrite-target: /$1 - 应用更新后的Ingress配置:
kubectl apply -f ingress.yaml
4. 验证Ingress Controller状态
确保Ingress NGINX Controller正常运行:
- 查看Controller Pod状态:
若Pod未就绪,重新安装Controller(Docker Desktop集群可使用官方静态部署文件):kubectl get pods -n ingress-nginxkubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/cloud/deploy.yaml
内容的提问来源于stack exchange,提问作者Davide Aprea
相关产品推荐
相关产品推荐

