在Ubuntu虚拟机中实现负载均衡常用工具为Nginx和HAProxy,以下是具体步骤:
sudo apt update
sudo apt install nginx
/etc/nginx/nginx.conf 或 /etc/nginx/conf.d/load_balancer.conf,添加后端服务器组及负载均衡策略(如轮询):http {
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
# 可选策略:least_conn(最少连接)、ip_hash(IP哈希)
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
}
sudo systemctl restart nginx
sudo apt update
sudo apt install haproxy
/etc/haproxy/haproxy.cfg,定义前端监听和后端服务器组: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
适用于高可用场景,需结合内核模块配置虚拟IP(VIP)和健康检查,步骤较复杂,可参考文档。
说明:
sudo nginx -t或sudo haproxy -f /etc/haproxy/haproxy.cfg测试配置语法。