Traefik is a modern, cloud-native HTTP reverse proxy and load balancer designed to easily manage ingress traffic in Kubernetes and other containerized environments. It dynamically discovers services and automatically configures itself. This document covers its key features, installation steps, and additional best practices for optimizing performance in Kubernetes clusters.
Add the official Traefik Helm repository and install it:
helm repo add traefik https://traefik.github.io/charts
helm repo update
helm install traefik traefik/traefik
Check if the Traefik pods are running:
kubectl get pods -n kube-system
Define an IngressRoute resource for routing traffic to a service:
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: my-service
namespace: default
spec:
entryPoints:
- web
routes:
- match: Host(`my-service.example.com`)
kind: Rule
services:
- name: my-service
port: 80
Ensure the routing is correctly configured:
kubectl get ingressroutes -n default
To enable automatic HTTPS certificates, configure Traefik with Let’s Encrypt support:
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: secure-service
namespace: default
spec:
entryPoints:
- websecure
tls:
certResolver: myresolver
routes:
- match: Host(`secure.example.com`)
kind: Rule
services:
- name: my-service
port: 443
Apply the configuration:
kubectl apply -f ingressroute-secure.yaml
If your service runs multiple replicas, Traefik automatically distributes traffic between them. However, for more control, you can specify weighted load balancing:
services:
- name: my-service
port: 80
weight: 2
- name: backup-service
port: 80
weight: 1
You can add authentication middleware to restrict access:
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: auth-middleware
namespace: default
spec:
basicAuth:
users:
- "admin:$apr1$randomhashvalue" # Use `htpasswd` to generate hashes
Apply the middleware and attach it to an IngressRoute :
routes:
- match: Host(`protected.example.com`)
kind: Rule
middlewares:
- name: auth-middleware
services:
- name: my-service
port: 80
If Traefik is not behaving as expected, check the logs:
kubectl logs -l app.kubernetes.io/name=traefik -n kube-system
Ensure Traefik detects the service and ingress correctly:
kubectl describe ingressroutes -n default
Check if the certificates are properly generated:
kubectl get certificates -n default
Traefik simplifies traffic management in Kubernetes environments with its dynamic service discovery, easy SSL integration, and advanced routing capabilities. By following these steps, you can deploy and configure Traefik to handle ingress traffic efficiently, enhance security with authentication middleware, and optimize traffic routing for high availability.