nginx负载均衡技术基础

  1. 首先需要在机子上安装nginx服务器,可以参照在Linux中安装nginx这篇文章来进行安装和初步地配置;

  2. 找到在主服务器上设置的静态资源文件夹的路径,比如,在swoole中就是在document_root这里定义的:

'document_root' => "/home/alexander/Documents/Refers/SwooleLive/server/thinkphp/public/static
  1. 之后进入到/config/nginx.conf文件中并对该文件中针对于nginx的配置进行更改,找到location配置项,这里需要注意的是nginx关于location的配置很多,需要找到server对应的那个location,详见如下(改的是第43行的这个路径):
server {
 36         listen       8023;
 37         server_name  localhost;
 38 
 39         #charset koi8-r;
 40 
 41         #access_log  logs/host.access.log  main;
 42 
 43         location / {
 44             root   html;
 45             index  index.html index.htm;
 46         }
 47 
 48         #error_page  404              /404.html;
 49 
 50         # redirect server error pages to the static page /50x.html
 51         #
 52         error_page   500 502 503 504  /50x.html;
 53         location = /50x.html {
 54             root   html;
 55         }
 ...        ...            
 n    }
  1. 将原先默认指向的html(这个是之前nginx服务器在安装完成之后指向的本地静态资源存储路径)改为我们主服务器的静态资源文件夹存放路径,也就是在“2.”这一步记录下来的路径。这样一来,所有关于静态资源的访问都是由nginx服务器处理而非由主服务器进行,这就是最简单的负载均衡案例。

  2. 在这个案例中,通过原先的服务器地址访问存储在静态资源目录下的文件能够正常访问到,使用nginx服务器的地址访问时也同样可以访问到,这里的负载均衡技术就是通过nginx服务器的地址访问主服务器的部分地址(如这个案例中的静态资源地址),开发过程中可以根据自己的需求对服务端的请求进行过滤,以最充分地利用负载均衡服务器(nginx服务器)和主服务器。

  3. 单纯通过上面的方法只是做到了最简单的负载均衡,那么如果说服务器的静态资源文件夹中没有指定的静态资源应该如何是好呢?答案就是将这个请求转发给主服务器

  4. 回到之前修改过的nginx配置文件nginx.conf中,找到之前改动过的location配置项,将其改为下方所示:

server {
 36         listen       8023;
 37         server_name  localhost;
 38 
 39         #charset koi8-r;
 40 
 41         #access_log  logs/host.access.log  main;
 42 
 43         #Locate to another server's static folder
 44         location / {
 45             root   /home/alexander/Documents/Refers/SwooleLive/server/thinkphp/public/static;
 46             index  index.html index.htm;
 47 
 48         #Be aware of the file-indent while writting this config file!!!
 49 
 50             #Check if the files don't exist on relevant folder
 51             if (!-e $request_filename) {
 52                 #Use the main-server's IP address to forward the client's response  
 53                 proxy_pass http://127.0.0.1:8811;
 54            }
 55         }
...      ...
n      }
  1. 撰写时一定要注意空格,if后面的括号前和括号后都需要空格。可以根据自己的需求,在这里定义各种转发方式,这里的proxy_pass是一个简单的示例,商业运行环境下这里的这个地址需要根据需求进行改动。



作者:艾孜尔江·艾尔斯兰
转载或使用请务必标明出处!

原文地址:https://www.cnblogs.com/ezhar/p/13677211.html