Categories

Tags

Nginx负载均衡

cd /nginx-1.10.3
./configure --with-http_stub_status_module
make

手上没有那么多主机,这里使用虚拟机来模拟
配置4台linux虚拟机,两台用于负载均衡,两台用于web服务

hostname ip 用途
lb01 192.168.1.227 负载均衡主机1
lb02 192.168.1.228 负载均衡主机2
web01 192.168.1.229 web主机1
web02 192.168.1.230 web主机2

修改本机hosts文件,添加一项

192.168.1.227    test.cn

给4台linux虚拟机都装上Nginx

web01和web02的nginx.conf,添加一个test.cn的server节点

server {
        listen       80;
        server_name test.cn;

        location / {
            root   /website/www/test;
            index  index.php index.html index.htm;
            if (!-e $request_filename){
                rewrite ^/(.*) /index.php last;
            }
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        location ~ \.php$ {
            root /website/www/test;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }

/website/www是web01和web02的web目录

web01和web02的/website/www/test文件夹新增index.php,内容如下

<?php  

$ip = '本机IP: '.$_SERVER['SERVER_ADDR'];  
echo $ip;exit;

web1的/etc/hosts添加一项

192.168.1.229 test.cn

web2的/etc/hosts添加一项

192.168.1.230 test.cn

配置lb01的nginx.conf文件,在http节点里面添加如下内容

    #自定义Web服务器池,包含两个Web节点
    upstream www_server_pools{
        server 192.168.1.229:80 weight=1;
        server 192.168.1.230:80 weight=1;
    }
    #定义代理的负载均衡域名虚拟主机
    server{
        listen 80;
        server_name test.cn;
        location /{
          #访问test.cn时会到www_server_pools里面查询节点
          proxy_pass http://www_server_pools;
        }
    }

现在打开本机浏览器,输入test.cn访问,刷新多次,有时可以看到ip为192.168.1.229,有时看到ip为192.168.1.230,说明已经启用负载均衡