Home > other >  Ingress and Angular with namespaces- how to reroute to correct namespace through ingress without cha
Ingress and Angular with namespaces- how to reroute to correct namespace through ingress without cha

Time:11-02

I'm currently building a K8s cluster with an angular app and express backend.

The cluster should be split into two namespaces, test and prod, with requests from the frontend in each ns going to the corresponding backend app. Because angular runs in the browser, I am currently sending requests from the angular app to the backend through an external ingress, but as angular environment variables are set at build time, I cannot specify different backendUrls for prod and test, so requests are sent to the same url no matter which namespace they came from.

I have seen a few people explaining that angular cannot reach the backend internally, but cannot find any info on how to sort out namespace routing. Is there a way for ingress to know where the request came from and reroute it accordingly? Or some other way to solve this problem.

my namespaces are set up as follows:

apiVersion: v1
kind: Namespace
metadata:
  name: test
---
apiVersion: v1
kind: Namespace
metadata:
  name: prod

And the ingress is set up like this on the prod namespace:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
  name: ingress-service
  namespace: prod
spec:
  ingressClassName: nginx
  rules:
    - host: prod.mysite.com
      http:
        paths:
          - backend:
              service:
                name: dashboard-service
                port:
                  number: 8081
            path: /?(.*)
            pathType: Prefix
          - backend:
              service:
                name: backend-service
                port:
                  number: 3000
            path: /api/?(.*)
            pathType: Prefix

And on the test namespace, it is identical but with host: test.mysite.com and namespace: prod. In each namespace, there is a dashboard app and a backend app with services.

I'm currently running this on minikube, but I expect the problem will continue when it is deployed on AWS.

Thanks a lot for any help you can give!

CodePudding user response:

You have basically three options:

  • Don't use the full URL in the angular app, just use /api/, when loading from the different URLs for prod.mysite.com/test.mysite.com the relative path will be appended to the domain and solves your issue
  • You can dynamically determine the backend url in Angular by inspecting the host name and/or port
  • You can create a docker image that changes the api url value which is defined in the index.html using an entrypoint and environment variables
  • Related