nginx安装与负载均衡配置

此篇介绍 nginx的安装所遇到的问题,以及负载均衡所遇到的问题。

nginx安装

1.安装必要的软件,pcre:可以支持rewrite功能。openssl:可以支持ssl功能。

<code># yum install pcre*
# yum install openssl*/<code>

2.从官网下载稳定版,此时是1.16.1,然后解压

<code># wget http://nginx.org/download/nginx-1.16.1.tar.gz
# tar -zxvf nginx-1.16.1.tar.gz/<code>

3.安装软件三板斧(./configure , make , make install)。注意nginx 1.9.5开始已经没有了 --with-http_spdy_module ,取代的是 --with-http_v2_module

nginx安装与负载均衡配置

安装nginx

  • –with-http_stub_status_module:支持 nginx 状态查询
  • –with-http_ssl_module:支持 https
  • –with-http_v2_module:支持 http2.0
  • –with-pcre:为了支持 rewrite 重写功能,必须制定 pcre
  • 4.centos7防火墙打开http

    <code># firewall-cmd --zone=public --add-service=http --permanent
    # firewall-cmd --reload/<code>

    启动nginx

    <code># /usr/local/nginx-1.16.1/sbin/nginx/<code>

    当通过你系统的IP地址访问出现如下画面,则安装成功

    nginx安装与负载均衡配置

    nginx安装成功

    关闭nginx:

    <code># /usr/local/nginx-1.16.1/sbin/nginx -s stop/<code>

    当改变了nginx.conf后,重置:

    <code># /usr/local/nginx-1.16.1/sbin/nginx -s reload/<code>

    nginx配置负载均衡

    我是用三个端口模拟(一个做反向代理,两个做WEB服务),分别为80(主),8000(子),8001(子)。这样可以不需要再另外配置三台服务器,仅作演示,有条件的可以直接弄三台。

    nginx安装与负载均衡配置

    负载均衡

    1、将防火墙允许这个三个端口访问(防火墙关闭的可以忽略)

    nginx安装与负载均衡配置

    开放端口

    2、新建两个目录,分别写入两个文件,作为两台WEB服务器的根目录

    <code># mkdir n1
    # mkdir n2
    # echo "node_1" > n1/index.html
    # echo "node_2" > n2/index.html/<code>

    3、修改nginx.conf文件,使两个端口(8000,8001)均可访问。如果出现

    403 Forbidden错误,请将nginx.conf的头部“user nobody;”修改为你目录的权限用户。

    <code># vim /usr/local/nginx-1.16.1/conf/nginx.conf/<code>
    nginx安装与负载均衡配置

    如下图所示:

    nginx安装与负载均衡配置

    4、再次修改nginx.conf,配置负载均衡,主要使用以下关键字“upstream , proxy_pass”。我这里使用的localhost,如果要使用,请改成自己的IP和端口。

    nginx安装与负载均衡配置

    当访问默认IP时,不断刷新出现如下图所示,即配置完成。

    nginx安装与负载均衡配置

    负载均衡的几种常用方式

    1、轮询(默认)。每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

    <code>upstream myload {
    \tserver localhost:8000;
    \tserver localhost:8001;
    }/<code>

    2、weight (权重)。当后端服务器的性能不同时,可以按比率分配。weight与访问比率成正比。

    <code>upstream myload {
    \tserver localhost:8000 weight=4;
    \tserver localhost:8001 weight=6;
    }/<code>

    3、当启用了session时,想让用户登录后,后续访问都在此台服务器上时可以用这种。

    <code>upstream myload {
    \tip_hash;
    \tserver localhost:8000;
    \tserver localhost:8001;
    }/<code>

    4、fair(第三方) 。这种需要安装模块“nginx-upstream-fair”。这里就不细讲,我会在nginx模块安装里详细介绍。只需知道fair采用的不是内建负载均衡使用的轮换的均衡算法,而是可以根据页面大小、加载时间长短智能的进行负载均衡。

    <code>upstream myload {
    \tserver localhost:8000;
    \tserver localhost:8001;
    \tfair;\t
    }/<code>

    5、url_hash(第三方)。这种需要配置缓存命中来使用。主要是进行缓存,对多个需要下载的资源(对应的url)进行缓存。

    <code>upstream myload {
    \thash $request_uri;
    \tserver localhost:8000;
    \tserver localhost:8001;
    }/<code>


    分享到:


    相關文章: