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

相关推荐
大海无量_94968几秒前
使用imapsync增量同步邮件到新邮局服务器
运维·服务器
bkspiderx1 分钟前
Linux网络与路由配置完全指南
linux·运维·网络·c++
2301_810730101 分钟前
Chrony服务器实验练习
运维·服务器
ssm11224 分钟前
ubuntu服务器无法识别所有显卡
运维·服务器·ubuntu
云道轩5 分钟前
解决 “默认的putty 很快就断开了,无法连接服务器”
运维·服务器
ximy13356 分钟前
AI服务器工作之系统下查看硬件(ubuntu为例)
运维·服务器·ubuntu
自由会客室1 小时前
Nginx 日志轮转
运维·服务器
天外非1 小时前
Linux密钥登录配置教程
运维·ssh
袁煦丞 cpolar内网穿透实验室1 小时前
N1+iStoreOS+cpolarN1盒子变身2048服务器:cpolar内网穿透实验室第653个成功挑战
运维·服务器·docker·远程工作·内网穿透·cpolar
云计算练习生1 小时前
linux shell编程实战 04 条件判断与流程控制
linux·运维·流程控制·shell编程·条件判断