在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集群并实现负载均衡。选择哪种方法取决于具体的需求和环境。