Create a Load Balancer
To ensure the stable operation of applications and evenly distribute traffic among pods in Kubernetes, you can use a load balancer. It helps avoid overloading individual pods, maintaining high availability and stability of services.
To create a load balancer in Kubernetes, we define a Service resource with the type LoadBalancer. Below is an example of a basic manifest:
apiVersion: v1
kind: Service
metadata:
name: example-balancer
namespace: kubernetes-dashboard
spec:
selector:
app.kubernetes.io/name: nginx
ports:
- port: 80 # External port for accessing the application
targetPort: 80 # Pod port to which traffic is redirected
type: LoadBalancer
In this example, the load balancer redirects traffic from port 80 to port 80 inside the pods matching the selector app.kubernetes.io/name: nginx.
If you need to add multiple rules for balancing, ensure that you specify the name attribute for each port:
apiVersion: v1
kind: Service
metadata:
name: example-balancer
namespace: kubernetes-dashboard
spec:
selector:
app.kubernetes.io/name: nginx
ports:
- port: 80
targetPort: 80
name: http
- port: 443
targetPort: 443
name: https
type: LoadBalancer
The value of the name attribute can be arbitrary.
For each port, you can specify the traffic protocol using the appProtocol attribute. This explicitly defines how the load balancer will handle traffic. By default, the value is proto-tcp.
The following values are supported:
k8s.hostman.com/proto-http: standard HTTP traffick8s.hostman.com/proto-https: HTTPS traffick8s.hostman.com/proto-tcp: TCP traffick8s.hostman.com/proto-tcp-ssl: TCP traffic with TLS supportk8s.hostman.com/proto-http2: HTTP/2 traffic
After creation, the load balancer will be visible in the management panel under the Load Balancers section, with a k8s label.