在CentOS上部署Kubernetes(k8s)集群并實現負載均衡,可以通過以下幾種方法:
安裝必要的軟件包:
在兩臺Master節點上安裝haproxy
和keepalived
。
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
啟動服務并設置為開機自啟: 在所有Master節點上執行以下命令。
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
Kubernetes提供了內置的負載均衡機制,主要通過Service資源類型來實現。
創建Service:
創建一個類型為LoadBalancer
的服務。
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 9376
type: LoadBalancer
創建Ingress資源: 對于外部流量的負載均衡,可以使用Ingress資源。
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
通過以上方法,可以在CentOS上部署Kubernetes集群并實現負載均衡。選擇哪種方法取決于具體的需求和環境。