在CentOS上配置Kubernetes(k8s)负载均衡可以通过多种方法实现,以下是一些常见的方案:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 9376
type: LoadBalancer
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
spec:
rules:
- http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
安装必要的软件包:
yum install haproxy keepalived -y
配置Keepalived:
编辑/etc/keepalived/keepalived.conf文件,配置VRRP实例和虚拟IP地址(VIP)。
global_defs {
router_id K8S-2
script_user root
enable_script_security
}
vrrp_script check_server {
script "/etc/keepalived/check.sh"
interval 3
weight -10
fall 2
rise 2
}
vrrp_instance VI_1 {
state MASTER
interface ens224
virtual_router_id 51
priority 100
advert_int 2
authentication {
auth_type PASS
auth_pass 123
}
virtual_ipaddress {
192.168.2.254/24
}
track_script {
check_server
}
}
编写检测脚本: 将检测脚本放在keepalived目录下,用于监控haproxy服务进程。
#!/usr/bin/env bash
if pgrep haproxy > /dev/null; then
true
else
systemctl stop keepalived.service
exit 1
fi
配置HAProxy:
编辑/etc/haproxy/haproxy.cfg文件,添加负载均衡配置。
global
log /dev/log
local0
local1
notice
maxconn 4096
tune.ssl.default-dh-param 2048
defaults
log global
mode http
option httplog
option dontlognull
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
frontend http-in
bind *:80
default_backend servers
backend servers
balance roundrobin
server server1 192.168.3.101:80
server server2 192.168.3.102:80
启动服务并设置为开机自启:
systemctl start haproxy.service
systemctl enable haproxy.service
systemctl start keepalived.service
systemctl enable keepalived.service
安装Nginx:
yum install nginx -y
配置Nginx:
编辑/etc/nginx/nginx.conf文件,添加负载均衡配置。
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
启动Nginx服务:
systemctl start nginx
systemctl enable nginx
部署要求:
工作原理: MetalLB包含Controller和Speaker两个组件,Controller以Deployment方式部署,Speaker以Daemonset方式部署在集群内部各个Node节点。 Controller监听Service变化,分配IP地址并管理其生命周期,Speaker根据选择的协议进行广播或应答,实现IP地址的通信响应。
部署安装: 通过Kubernetes清单、Helm或Kustomize方式部署MetalLB。
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/master/manifests/metallb.yaml
以上方法可以在CentOS上利用Kubernetes实现高效的负载均衡,提升应用的可用性和性能。选择合适的方案取决于具体的需求和环境。