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

相关推荐
qq_5895681016 分钟前
centos6.8镜像源yum install不成功,无法通过镜像源下载的解决方式
linux·运维·centos
weixin_516023071 小时前
linux下fcitx5拼音的安装
linux·运维·服务器
hunter14501 小时前
Linux 进程与计划任务
linux·运维·服务器
楼田莉子2 小时前
Linux学习之磁盘与Ext系列文件
linux·运维·服务器·c语言·学习
陌上花开缓缓归以2 小时前
linux 怎么模拟系统panic重启
linux·运维·服务器
月白风清江有声2 小时前
vscode使用git
linux·运维·服务器
haluhalu.4 小时前
深入理解Linux线程机制:线程概念,内存管理
java·linux·运维
cui__OaO5 小时前
Linux驱动--驱动编译
linux·运维·服务器
Q16849645156 小时前
红帽Linux-进程、ssh、网络、软件包、文件系统
linux·运维·网络
ℳ₯㎕ddzོꦿ࿐6 小时前
Docker 环境下 Paperless-ngx 中文增强版部署实战
运维·docker·容器