负载均衡(Load Balancing)是将网络流量分配到多个服务器上的技术,主要目的是: - 提高系统整体性能 - 增强系统可靠性 - 实现无缝扩展
安装Nginx:
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
基本配置 (/etc/nginx/nginx.conf
):
http {
upstream backend {
server 192.168.1.101:80 weight=5;
server 192.168.1.102:80;
server 192.168.1.103:80 backup;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
负载均衡算法: - 轮询(默认) - 加权轮询(weight) - IP哈希(ip_hash) - 最少连接(least_conn)
安装HAProxy:
sudo yum install haproxy
sudo systemctl start haproxy
sudo systemctl enable haproxy
基本配置 (/etc/haproxy/haproxy.cfg
):
frontend http_front
bind *:80
stats uri /haproxy?stats
default_backend http_back
backend http_back
balance roundrobin
server server1 192.168.1.101:80 check
server server2 192.168.1.102:80 check
server server3 192.168.1.103:80 check
安装LVS:
sudo yum install ipvsadm
配置示例:
# 添加虚拟服务
ipvsadm -A -t 192.168.1.100:80 -s rr
# 添加真实服务器
ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.101:80 -g
ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.102:80 -g
Nginx健康检查:
upstream backend {
server 192.168.1.101:80 max_fails=3 fail_timeout=30s;
server 192.168.1.102:80 max_fails=3 fail_timeout=30s;
check interval=5000 rise=2 fall=3 timeout=1000 type=http;
check_http_send "HEAD / HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
HAProxy健康检查:
backend http_back
option httpchk GET /health
http-check expect status 200
server server1 192.168.1.101:80 check inter 5s fall 3 rise 2
Nginx IP哈希:
upstream backend {
ip_hash;
server 192.168.1.101:80;
server 192.168.1.102:80;
}
HAProxy Cookie插入:
backend http_back
balance roundrobin
cookie SERVERID insert indirect nocache
server server1 192.168.1.101:80 cookie s1 check
server server2 192.168.1.102:80 cookie s2 check
内核参数调优 (/etc/sysctl.conf
):
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
Nginx性能优化:
worker_processes auto;
worker_rlimit_nofile 100000;
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
连接池优化:
upstream backend {
server 192.168.1.101:80;
keepalive 32;
}
server {
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
实时监控:
# Nginx状态
nginx -t
nginx -s reload
# HAProxy状态
watch -n 1 'echo "show stat" | socat /var/run/haproxy.sock stdio'
日志分析:
自动化部署:
通过以上配置和优化,您可以在CentOS上构建一个高性能、可靠的负载均衡Web服务器架构。