Traffic Routing Rules
Types of Routing in Kubernetes Ingress
graph TD
A[Routing Rules] --> B[Path-based Routing]
A --> C[Host-based Routing]
A --> D[Rewrite and Redirect]
Path-based Routing
Path-based routing allows you to direct traffic to different services based on the URL path.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: path-routing
spec:
rules:
- host: myapp.labex.io
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: users-service
port:
number: 80
- path: /products
pathType: Prefix
backend:
service:
name: products-service
port:
number: 80
Host-based Routing
Host-based routing enables routing traffic to different services based on the request's hostname.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: host-routing
spec:
rules:
- host: users.labex.io
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: users-service
port:
number: 80
- host: products.labex.io
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: products-service
port:
number: 80
Routing Rule Configurations
Configuration |
Description |
Use Case |
Prefix Match |
Matches paths starting with specified prefix |
General routing |
Exact Match |
Matches exact path |
Precise routing |
Wildcard Match |
Matches paths with wildcards |
Complex routing |
Rewrite and Redirect Rules
Ingress supports advanced routing techniques like URL rewriting and redirects.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: rewrite-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: myapp.labex.io
http:
paths:
- path: /app/(.*)
pathType: Prefix
backend:
service:
name: app-service
port:
number: 80
Advanced Routing Strategies
SSL/TLS Termination
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: tls-example
spec:
tls:
- hosts:
- myapp.labex.io
secretName: tls-secret
rules:
- host: myapp.labex.io
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: app-service
port:
number: 80
Load Balancing Strategies
Ingress controllers support multiple load balancing algorithms:
- Round Robin
- Least Connections
- IP Hash
Best Practices
- Use specific path types
- Implement proper authentication
- Configure timeouts
- Monitor ingress performance
- Use annotations for advanced configurations
By mastering these routing rules, you can create sophisticated traffic management strategies in your Kubernetes cluster.