I have 3 services in 3 different namespaces I want my ingress rules to map to these backends, on path based routes. Can someone please guide on the same. I am using nginx ingress inside azure Kubernetes cluster.
How to create nginx ingress rules for services in 3 different namespaces in azure Kubernetes cluster
Asked
Active
Viewed 647 times
1
-
1Have you tried to create `Ingress` resource **for each `namespace`** with the routes to the specific services? – Dawid Kruk Oct 01 '22 at 16:30
1 Answers
1
A basic example with an assumption that your nginx ingress
is working correctly inside your AKS
would be following:
List of Pods
with their Services
:
Pod | Namespace | Service name |
---|---|---|
nginx | alpha | alpha-nginx |
nginx | beta | beta-nginx |
nginx | omega | omega-nginx |
Ingress
definition for this particular setup:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: alpha-ingress
namespace: alpha
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
ingressClassName: nginx
rules:
- host: "kubernetes.kruk.lan"
http:
paths:
- path: /alpha(/|$)(.*)
pathType: Prefix
backend:
service:
name: alpha-nginx
port:
number: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: beta-ingress
namespace: beta
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
ingressClassName: nginx
rules:
- host: "kubernetes.kruk.lan"
http:
paths:
- path: /beta(/|$)(.*)
pathType: Prefix
backend:
service:
name: beta-nginx
port:
number: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: omega-ingress
namespace: omega
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
ingressClassName: nginx
rules:
- host: "kubernetes.kruk.lan"
http:
paths:
- path: /omega(/|$)(.*)
pathType: Prefix
backend:
service:
name: omega-nginx
port:
number: 80
In this example Ingress
will analyze and rewrite the requests for the same domain name to send the traffic to different namespaces i.e. alpha
, beta
, omega
.
When you've have finalized your Ingress
resource, you can use curl
to validate your configuration.
curl kubernetes.kruk.lan/alpha | grep -i "<h1>"
<h1>Welcome to nginx from ALPHA namespace!</h1>
curl kubernetes.kruk.lan/beta | grep -i "<h1>"
<h1>Welcome to nginx from BETA namespace!</h1>
curl kubernetes.kruk.lan/omega | grep -i "<h1>"
<h1>Welcome to nginx from OMEGA namespace!</h1>
I'd encourage you to check following docs on rewrites:
PS: Pods
are default nginx
containers/images with added text to /usr/share/nginx/html/index.html

Dawid Kruk
- 8,982
- 2
- 22
- 45
-
Will it work the same without host as well as I am using just in no host defined – Abhishek Singh Oct 04 '22 at 15:03
-
@AbhishekSingh If you do not put `host` in the `Ingress` definition then your `Ingress` controller will "ignore" the `Host` header. Basically it will accept every request and push it to the relevant backend (according to the paths). – Dawid Kruk Oct 04 '22 at 15:58