欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > NGINX七层负载均衡配置方案

NGINX七层负载均衡配置方案

2025/2/24 13:16:29 来源:https://blog.csdn.net/thetender/article/details/141067531  浏览:    关键词:NGINX七层负载均衡配置方案

NGINX

  • 一、准备
  • 二、配置NGINX服务器
    • 1. 下载NGINX
    • 2. 编写配置文件
    • 3. 启动NGINX服务
  • 三、配置后端服务
    • ①配置web服务器
    • ②配置php服务器
  • 四、测试

一、准备

  • 准备5台CentOS7服务器,IP地址如下:
    • HAproxy 192.168.152.71
    • web1 192.168.152.72
    • web2 192.168.152.73
    • php1 192.168.152.74
    • php2 192.168.152.75

二、配置NGINX服务器

1. 下载NGINX

yum install -y nginx

2. 编写配置文件

vim /etc/nginx/nginx.conf

编写内容如下:

  • 在 http 块中

    # 定义处理 .html 文件的上游服务器组
    upstream htmlservers {# 权重 1 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒)server 192.168.152.72:80 weight=1 max_fails=2 fail_timeout=2;# 权重 2 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒)server 192.168.152.73:80 weight=2 max_fails=2 fail_timeout=2;
    }# 定义处理 .php 文件的上游服务器组
    upstream phpservers {# 权重 1 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒)server 192.168.152.74:80 weight=1 max_fails=2 fail_timeout=2;# 权重 2 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒)server 192.168.152.75:80 weight=2 max_fails=2 fail_timeout=2;
    }
    
  • 在server块中

    # 匹配所有请求,默认请求,没有定义的请求全部走这个服务器
    location / {proxy_pass http://htmlservers;
    }# 对所有以 .html 结尾的请求进行处理
    location ~* \.html$ {# 将请求转发到 htmlservers 服务器组proxy_pass http://htmlservers;
    }# 对所有以 .php 结尾的请求进行处理
    location ~* \.php$ {# 将请求转发到 phpservers 服务器组proxy_pass http://phpservers;
    }
    
  • 关于权重 weight

    • 权重相同时采用 轮询算法:请求会按顺序依次分配到服务器组中的每台服务器。
    • 权重不同时采用 加权轮询算法:根据各个服务器的权重值来分配请求。权重越高的服务器会处理更多的请求。

3. 启动NGINX服务

systemctl start nginx && systemctl enable nginx

三、配置后端服务

①配置web服务器

测试用简单配置,web1 和 web2 都要配置

  1. 安装http服务
    yum install -y httpd
    
  2. 编写主页
    web1:
    echo web1 > /var/www/html/index.html
    
    web2:
    echo web2 > /var/www/html/index.html
    
  3. 启动http服务
    systemctl start httpd && systemctl enable httpd
    

②配置php服务器

测试用简单配置,php1 和 php2 都要配置

  1. 安装 php 和 http 服务
    yum install -y httpd php
    
  2. 编写主页
    php1:
    echo php1 > /var/www/html/index.php
    
    php2:
    echo php2 > /var/www/html/index.php
    
  3. 启动服务
    systemctl start httpd && systemctl enable httpd
    

四、测试

  • 可以在浏览器分别输入:
    • http://192.168.152.71
    • http://192.168.152.71/index.html
    • http://192.168.152.71/index.php

多次刷新,查看结果,前两个的结果为 web1,web2;最后一个结果为 php1,php2。
如果配置没有问题,但多次刷新无果,可能是浏览器缓存,可以用命令 elinks
下载 yum insdall -y elinks

elinks --dump http://192.168.152.71
elinks --dump http://192.168.152.71/index.html
elinks --dump http://192.168.152.71/index.php

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词