How to Use Host Based Routing Ingress in Kubernetes
Use a
kubernetes Ingress resource with rules specifying different host values. Each host routes traffic to a specific service inside the cluster, enabling host based routing.Syntax
An Ingress resource uses rules to define host based routing. Each rule has a host field and http.paths that specify which service to send traffic to.
- host: The domain name to match in the request.
- http: Contains
pathsfor routing. - paths: List of URL paths and backend services.
- backend.service.name: The Kubernetes service to route to.
- backend.service.port.number: The port of the service.
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: example-service
port:
number: 80
- host: test.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: test-service
port:
number: 80
Example
This example shows an Ingress that routes requests to example.com to example-service and requests to test.com to test-service. Each service listens on port 80.
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: host-routing-ingress
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: example-service
port:
number: 80
- host: test.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: test-service
port:
number: 80
Output
ingress.networking.k8s.io/host-routing-ingress created
Common Pitfalls
- Not specifying
hostin rules causes all hosts to route to the same backend. - Forgetting to set
pathTypecan cause routing issues; usePrefixfor most cases. - Ingress controller must support host based routing; check your controller documentation.
- DNS must point the hostnames to the Ingress controller's external IP.
yaml
Wrong example (missing host):
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: wrong-ingress
spec:
rules:
- http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
Right example (with host):
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: correct-ingress
spec:
rules:
- host: mysite.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
Quick Reference
- Use
hostin Ingress rules to route by domain name. - Set
pathTypetoPrefixfor path matching. - Ensure your DNS points to the Ingress controller IP.
- Verify your Ingress controller supports host based routing.
Key Takeaways
Define multiple
rules with different host values in your Ingress to enable host based routing.Always specify
pathType as Prefix for common path matching behavior.Make sure DNS entries for your hosts point to the Ingress controller's external IP.
Check that your Ingress controller supports host based routing before configuring.
Avoid missing
host fields to prevent routing all traffic to a single backend.