Nginx负载均衡主备模式

1. 背景

使用Nginx代理后端服务,有时候某些服务是不能使用多台负载均衡,但又想保障高可用,所以采用主备模式,记录如下:

2. 参考

3. 环境

  • Ubuntu 22.04
  • 三台虚拟机
    • 虚机Virtual-Machine-114,配置Nginx,nginx version: nginx/1.18.0 (Ubuntu)
    • 虚机Virtual-Machine-203,启动后端服务
    • 虚机Virtual-Machine-205,启动后端服务

4. 部署

4.1 配置Nginx

  • 虚机Virtual-Machine-114 安装nginx
bash 复制代码
apt install nginx
  • 查找nginx配置文件路径
bash 复制代码
whereis nginx
bash 复制代码
# whereis 执行结果
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz
  • 添加虚拟主机
bash 复制代码
cd /etc/nginx/conf.d && vim py_server.conf 
bash 复制代码
  # 定义upstream  
  upstream  python_server {
             # server指令指定后端服务器的IP地址和端口
             server    172.31.1.114:8084 down;  # 不参加负载均衡
             server    172.31.1.203:8083 max_fails=5  fail_timeout=60s; # 当检查后端服务5次失败(每1秒检查一次),判定后端服务不可用,然后60秒内不再检查。
             server    172.31.1.205:8085 backup;  # 备份节点,在所有提供服务节点均不可用时启用
            }

  # 定义server
  server {
             # 监听端口8080
             listen       8080;
             server_name  localhost;

             location / {
                           # 代理转发,服务转发至upstream python_server
                           proxy_pass http://python_server;
                        }
          }

4.2 配置后端服务

  • 虚机Virtual-Machine-203,创建html文件
    • 写入 "This is Server master, IP 172.31.1.203"
bash 复制代码
root@Virtual-Machine-203:/home/sj-test1/html# echo "This is Server master, IP 172.31.1.203" > serverinfo.html 
  • 虚机Virtual-Machine-203,启动服务
bash 复制代码
# 监听端口与上述配置一致
python3 -m http.server 8083
  • 虚机Virtual-Machine-205,创建html文件
    • 写入 "This is Server backup, IP 172.31.1.205"
bash 复制代码
root@Virtual-Machine-205:/home/sj-test1/html# echo "This is Server backup, IP 172.31.1.205" > serverinfo.html 
  • 虚机Virtual-Machine-205,启动服务
bash 复制代码
# 监听端口与上述配置一致
python3 -m http.server 8085

4.3 重启Nginx服务

  • 虚机Virtual-Machine-114重启nginx服务
bash 复制代码
service nginx restart

5. 测试

5.1 直接访问后端服务

5.2 访问Nginx代理服务

  • Nginx默认转发到172.31.1.203的后端服务上

  • 关闭虚机Virtual-Machine-203上的后端服务

  • 再次访问Nginx,已转发到172.31.1.205(backup)的后端服务上
    - 重新启动虚机Virtual-Machine-203上的后端服务,60秒后Nginx再次转发到172.31.1.203

6. 总结

通过配置Nginx配置文件,,定义upstream中每个后端Server的状态,可以实现后端服务的主备负载均衡。在上述测试中使用的是默认轮询算法。注意!ip_hash算法不支持backup状态定义。

相关推荐
獭.獭.18 分钟前
Linux -- 信号【上】
linux·运维·服务器
hashiqimiya21 分钟前
centos配置环境变量jdk
linux·运维·centos
路由侠内网穿透2 小时前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
傻傻虎虎3 小时前
【Docker】常用帮忙、镜像、容器、其他命令合集(2)
运维·docker·容器
ZERO_pan4 小时前
服务器装机遇到的问题
运维·服务器
杀气丶4 小时前
Linux下运行芙蕾雅天堂2【俄文简译L2FATER】
运维·服务器·天堂2·l2fater·l2fater.cn
太空的旅行者5 小时前
告别双系统——WSL2+UBUNTU在WIN上畅游LINUX
linux·运维·ubuntu
九章云极AladdinEdu6 小时前
超参数自动化调优指南:Optuna vs. Ray Tune 对比评测
运维·人工智能·深度学习·ai·自动化·gpu算力
人工智能训练师7 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Tisfy9 小时前
服务器 - 从一台服务器切换至另一台服务器(损失数十条访客记录)
运维·服务器