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状态定义。

相关推荐
无情的西瓜皮5 小时前
MCP协议实战:从零搭建一个AI Agent工具服务器
运维·服务器·python
Do_GH6 小时前
【Linux】09.WSL+SVN部署操作说明
linux·运维·svn
哈德森hh6 小时前
我的 Twitter 自动化运营流程
运维·自动化·twitter
ElevenS_it1886 小时前
连锁门店IT运维监控实战:200+门店网络设备+POS统一纳管+按区域分组告警路由完整配置(Zabbix Proxy架构)
运维·网络·架构·zabbix
dualven_in_csdn6 小时前
mqtt消息及日志查看
linux·运维·服务器
呉師傅6 小时前
东芝e-STUDIO 3525ac提示黄色和品红色墨粉盒在耗尽前被更换。请重新插入之前的墨粉盒并用至耗尽如何操作
运维·windows·电脑
都在酒里6 小时前
Linux字符设备驱动开发(四):进入硬件世界——GPIO子系统与LED设备驱动
linux·运维·驱动开发
Yupureki7 小时前
《MySQL数据库基础》9.索引原理
linux·运维·服务器·网络·数据库·mysql
2301_809051147 小时前
Linux TCP 和 UDP 通信
linux·运维·tcp/ip
Qt程序员7 小时前
从上电到系统就绪:ARM+U-Boot 嵌入式 Linux 启动流程
linux·运维·c++·内核·设备树·嵌入式·ram