在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實現高效的負載均衡,提升應用的可用性和性能。選擇合適的方案取決于具體的需求和環境。