Junior — Middle
How do you implement and configure load balancers in Kubernetes for traffic distribution?
sobes.tech AI
Answer from AI
In Kubernetes, objects of type Service with LoadBalancer or Ingress are typically used for load balancing.
- LoadBalancer type Service creates an external load balancer (e.g., in the cloud) that distributes traffic to pods.
- Ingress manages HTTP/HTTPS traffic and allows setting routing and load balancing rules.
Example of configuring a Service with LoadBalancer:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: LoadBalancer
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
For more flexible load balancing, Ingress controllers (e.g., NGINX Ingress Controller) can be used, where routing rules, SSL, URL rewriting, etc., are configured.
It is also important to set readiness and liveness probes for pods so that the load balancer directs traffic only to healthy instances.