Basics of Kubernetes Ingress
In Kubernetes, Ingress manages external access to services within a cluster. It provides HTTP and HTTPS routes to services based on a set of rules.
How It Works
- The Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster.
- Traffic routing is controlled by rules defined in the Ingress resource.
kubectl get ingress
This command will list all Ingress resources in the current namespace.
Ingress Controllers: Nginx, Traefik, etc.
An Ingress controller is responsible for fulfilling the Ingress, and you must have one running to use Ingress. Popular options include Nginx, Traefik, and Istio.
Nginx
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller/main/deploy/static/provider/cloud/deploy.yaml
Traefik
kubectl apply -f https://github.com/traefik/traefik-helm-chart/tree/master/traefik
Defining Ingress Rules
You can define rules to specify how to route traffic to services.
Here’s an example Ingress YAML file:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: example-service
port:
number: 80
Apply it with:
kubectl apply -f example-ingress.yaml
SSL/TLS and Ingress
You can secure Ingress by specifying a secret that contains an SSL certificate and key.
Here’s how to add a TLS section to your Ingress YAML:
spec:
tls:
- hosts:
- myapp.example.com
secretName: myapp-certificate
To create a self-signed certificate for testing:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout myapp.key -out myapp.crt
kubectl create secret tls myapp-certificate --key myapp.key --cert myapp.crt
Troubleshooting and Best Practices
-
Check Ingress Controller Logs:
kubectl logs -n <namespace> <ingress-controller-pod>
-
Describe Ingress Resource:
kubectl describe ingress <ingress-name>
-
Best Practices:
- Always specify a host in your Ingress rules.
- Use path-based routing for directing traffic to different services.
- Use HTTPS for secure communication.
Complete Exercise
Setup
- Deploy an example service:
kubectl run example-service --image=nginx --port=80
kubectl expose pod example-service --port=80
Steps
- Create an Ingress YAML file based on the example above.
- Apply the Ingress YAML:
kubectl apply -f example-ingress.yaml
- Test the Ingress rule:
curl myapp.example.com
Troubleshooting
- If it doesn’t work, describe the Ingress and check logs:
kubectl describe ingress example-ingress
kubectl logs -n <namespace> <ingress-controller-pod>
Solution
If all steps are followed correctly, you should be able to access the example-service
via myapp.example.com
.