1. 机器准备
|-------|------------|
| 客户端 | 10.0.0.205 |
| nginx | 10.0.0.206 |
| web1 | 10.0.0.203 |
| web2 | 10.0.0.204 |
2. nginx 服务配置
下载 nginx
[root@ubuntu2204 ~]# apt install nginx -y
编辑配置文件,将请求分发到后端服务器
[root@ubuntu2204 ~]# vim /etc/nginx/conf.d/load_balance.conf
upstream backend_servers {
server 10.0.0.203:8081 weight=2; # 权重为 2
server 10.0.0.204:8082 weight=1; # 权重为 1
}
server {
listen 81;
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
}
}
检查配置
[root@ubuntu2204 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重启 nginx 服务
[root@ubuntu2204 ~]# systemctl restart nginx.service
3. 后端服务器准备
创建第一个后端服务
[root@ubuntu2204 ~]# mkdir -p /var/www/backend1
[root@ubuntu2204 ~]# echo "Backend Server 1" > /var/www/backend1/index.html
[root@ubuntu2204 ~]# python3 -m http.server 8081 --directory /var/www/backend1 &
创建第二个后端服务
[root@ubuntu2204 ~]# mkdir -p /var/www/backend2
[root@ubuntu2204 ~]# echo "Backend Server 2" > /var/www/backend2/index.html
[root@ubuntu2204 ~]# python3 -m http.server 8082 --directory /var/www/backend2 &
验证后端服务是否正常运行
[root@ubuntu2204 ~]# curl http://10.0.0.203:8081
Backend Server 1
[root@ubuntu2204 ~]# curl http://10.0.0.204:8082
Backend Server 2
4. 测试负载均衡
[root@ubuntu2204 ~]# for i in {1..10};do curl http://10.0.0.206:81;done
Backend Server 2
Backend Server 1
Backend Server 1
Backend Server 2
Backend Server 1
Backend Server 1
Backend Server 2
Backend Server 1
Backend Server 1
Backend Server 2
5. 健康检查
停止一个服务,测试nginx是否能检测到异常,并合理分发请求
[root@ubuntu2204 ~]# pkill -f "python3 -m http.server 8081"
客户端继续访问后端服务
[root@ubuntu2204 ~]# for i in {1..10};do curl http://10.0.0.206:81;done
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2
Backend Server 2