Kubernetes nginx route traffic to /api/*

Viewed 78

I have a kubernetes cluster with configured nginx to port traffic to my angular application. It is working fine, however when I access the myipaddress/api/v1 - I want nginx to port the traffic to my express application which is listening on port 3000 and the angular application not to look the myipaddress/api/v1 as a route component in angular as it doesn't exist.

Here's my kubernetes nginx ingress for express

apiVersion: v1
kind: Service
metadata:
  name: backend
spec:
  type: ClusterIP
  ports:
  - port: 3000
    targetPort: 3000
  selector:
    app: backend

---

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: backend-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /api/?(.*)
        pathType: Prefix
        backend:
          service:
            name: backend
            port:
              number: 3000

Here's my ingress for angular

---
apiVersion: v1
kind: Service
metadata:
  name: webapp
spec:
  type: ClusterIP
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: webapp

--- 
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: webapp-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: webapp
            port:
              number: 80

What I am trying to achieve for angular

myipaddres.com        -> serve angular application`
myipaddress.com/users -> serve angular router for /users

What I am trying to achieve for express:

myipaddress.com/api/v1/users -> call the users v1 endpoint in express
myipaddress.com/api/v2/users -> call the users v2 endpoint in express
1 Answers

Ok I managed to find the solution myself, posting this in case someone needs it. The newest api for kubernetes (up to date of posting this) supports regex but you should explicitly enable it with annotation.

---
# ingress traffic
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: backend-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true" # enabling regex annotation
spec:
  rules:
  - http:
      paths:
      - path: /api/*      # works fine with regex enabled
        pathType: Prefix
        backend:
          service:
            name: backend
            port:
              number: 3000

The same applies for any other ingress path you need to reverse proxy.

Related