在CentOS上進行負載均衡可以通過多種方法實現,常見的包括使用LVS、Nginx和Haproxy等工具。以下是使用Nginx和LVS在CentOS上進行負載均衡的詳細步驟:
sudo yum install epel-release -y
sudo yum install nginx -y
編輯Nginx配置文件,通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/default.conf
。
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
# 添加更多后端服務器
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
sudo systemctl start nginx
sudo systemctl enable nginx
訪問服務器的IP地址和端口,查看是否能按預期進行負載均衡。
sudo yum install ipvsadm -y
# 清除iptables規則
sudo iptables -F
# 設置內核參數
echo "1" > /proc/sys/net/ipv4/ip_forward
# 添加虛擬服務器
sudo ipvsadm -A -t VIP:端口 -s rr
# 添加真實服務器
sudo ipvsadm -a -t VIP:端口 -r RSIP:端口 -g
其中,VIP
是虛擬IP地址,RSIP
是后端服務器的IP地址,端口
是服務的端口號。
sudo yum install haproxy -y
編輯Haproxy配置文件,通常位于 /etc/haproxy/haproxy.cfg
。
global
log /dev/log local0
log /dev/log 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.0.101:80 check
server server2 192.168.0.102:80 check
sudo systemctl start haproxy
sudo systemctl enable haproxy
通過瀏覽器或命令行工具訪問Haproxy服務器的IP地址和端口,查看是否能按預期進行負載均衡。