Sub topic 12
LoadBalancer: cloud load balancers
A LoadBalancer Service exposes your Pods outside the cluster through an external load balancer. This chapter assumes you know ClusterIP and NodePort Services, label selectors, and how a Deployment creates Pods. It builds on the web Deployment from earlier chapters.
What a LoadBalancer Service does
A LoadBalancer Service is a NodePort Service plus a request to the cloud provider. Kubernetes allocates a ClusterIP and a NodePort first. A controller then creates an external load balancer that forwards traffic to those node ports.
apiVersion: v1
kind: Service
metadata:
name: web-public
spec:
type: LoadBalancer
selector:
app: web
ports:
- name: http
port: 80
targetPort: httpThe provisioning is done by the cloud controller manager, which is part of your cloud provider's integration. On a cluster without one, such as a bare local cluster, the Service stays in a pending state. Add-ons such as MetalLB fill this gap on bare metal.
How traffic flows
The load balancer picks a node. kube-proxy on that node then picks a Pod, which may run on a different node.
Checking the result
Apply the manifest and watch the Service until an address appears:
kubectl apply -f web-public.yaml
kubectl get service web-public --watchThe EXTERNAL-IP column shows <pending> until the cloud finishes provisioning. Depending on the provider, the value is an IP address or a hostname. Then send a request to it:
curl http://EXTERNAL-IP/Replace EXTERNAL-IP with the value from the output.
Provider-specific settings
Cloud providers expose options through annotations on the Service, for example to make a load balancer internal or to choose its type. These annotations differ between providers, so check your provider's documentation. The Service spec also has loadBalancerSourceRanges, which restricts the client IP ranges allowed to connect, and externalTrafficPolicy, which a later chapter covers.
Common errors
- EXTERNAL-IP stays pending. The cluster has no cloud controller or load balancer implementation, or the provider rejected the request. Run
kubectl describe service web-publicand read the Events. - Connections time out. Check that the Pods are ready and appear in the EndpointSlices. Also check that firewall rules allow traffic from the load balancer to the node ports.
- Cost surprises. Each LoadBalancer Service usually creates its own cloud load balancer, which you pay for. For many HTTP apps, one Ingress is cheaper than many LoadBalancer Services.
Exercise
You create a LoadBalancer Service on a local cluster with no cloud integration, and EXTERNAL-IP stays at <pending>. Is the Service broken? How can you still reach the app?
Show answer
The Service is not broken. Nothing is available to provision the external load balancer. The ClusterIP and NodePort still work, so you can reach the app through any node's IP on the allocated node port, or install a load balancer implementation such as MetalLB.