在Ubuntu中实现负载均衡常用工具包括Nginx、HAProxy等,以下是具体方法及配置要点:
sudo apt update && sudo apt install nginx
/etc/nginx/nginx.conf 或 /etc/nginx/conf.d/load_balancer.conf,添加 upstream 块定义后端服务器组,支持轮询、权重、IP哈希等算法。http {
upstream backend {
server 192.168.1.101:80;
server 192.168.1.102:80;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
}
sudo systemctl restart nginx
sudo systemctl enable nginx
sudo apt update && sudo apt install haproxy
/etc/haproxy/haproxy.cfg,在 frontend 和 backend 中定义虚拟IP、后端服务器及负载均衡算法(如 roundrobin)。frontend http_front
bind *:80
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
sudo systemctl restart haproxy
sudo systemctl enable haproxy
ipvsadm,配置虚拟IP和负载均衡规则,适合高并发场景。docker-compose.yml 定义多容器服务,利用内置负载均衡分发请求。max_fails 和 fail_timeout 参数,自动剔除故障服务器。worker_processes、worker_connections 等参数提升并发能力。根据实际需求选择工具,Nginx适合Web应用,HAProxy适合TCP/HTTP协议,LVS适合大规模集群。