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

相关推荐
Kaede627 分钟前
如何应对Linux云服务器磁盘空间不足的情况
linux·运维·服务器
Kookoos3 小时前
Dynamics 365 Finance + Power Automate 自动化凭证审核
运维·自动化·dynamics 365·power automate
努力学习的小廉7 小时前
深入了解linux系统—— 进程池
linux·运维·服务器
秃头菜狗7 小时前
各个主要目录的功能 / Linux 常见指令
linux·运维·服务器
jiunian_cn9 小时前
【Linux】centos软件安装
linux·运维·centos
藥瓿亭9 小时前
K8S认证|CKS题库+答案| 6. 创建 Secret
运维·ubuntu·docker·云原生·容器·kubernetes·cks
2302_809798329 小时前
【JavaWeb】Docker项目部署
java·运维·后端·青少年编程·docker·容器
嵌入式大圣9 小时前
Neko虚拟浏览器远程协作方案:Docker+内网穿透技术部署实践
运维·docker·容器
dmy9 小时前
n8n内网快速部署
运维·人工智能·程序员
程序员JerrySUN10 小时前
全面理解 Linux 内核性能问题:分类、实战与调优策略
java·linux·运维·服务器·单片机