kuberneteskubernetes-ingressingress-nginx

502 Bad Gateway: Unable to Access Kubernetes Pods via Ingress NGINX


I'm trying to set up Ingress NGINX on a local Kubernetes cluster (using Docker Desktop for Windows with Kubernetes enabled) to expose multiple microservices, but I'm encountering "502 Bad Gateway" errors with "connect() failed (111: Connection refused)" and "Service 'default/auth-cluster-ip' does not have any active Endpoint" in the Ingress NGINX logs.

The Kubernetes object configurations are done using YAML files.

Here's my Ingress NGINX configuration yaml:

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

And here's the deployment and service config for the auth section, for reference:

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

I also updated the hosts file with this line: 127.0.0.1 instagram-clone.dev

Here's my node.js auth microservice index.js:

export const app = express();

app.use(json());

app.use("/", authRouter);

Debugging Steps Taken:


Solution

  • The error was related to how I defined the path in the microservice. I initially thought that every request matching the base URL defined in the ingress file would be forwarded to the correct pod, with the rest of the URL being handled by the microservice itself. I simply misunderstood how route definitions in the ingress configuration actually work. The correct path definition for mounting the route is:

    app.use("/v1/auth", authRouter);
    

    just like defined in the Ingress config file.

    Hope this can be helpful for someone.