通过nginx搭建负载均衡,这里通过这个upstream模块来实现,在nginx.org的官网可以看到相应的模块

proxy模块也可以实现负载均衡。

 

第一、打开lamp和lnmp  两个web服务器

Nginx-proxy这台服务器安装nginx,负载均衡需要nginx

安装nginx1.6.2



tar -xf nginx-1.6.2.tar.gz 

ls

cd nginx-1.6.2

useradd -s /sbin/nologin -M nginx

./configure --user=nginx --group=nginx --prefix=/usr/local/nginx1.6.2 --with-http_stub_status_module --with-http_ssl_module

make

make install

ln -s /usr/local/nginx1.6.2/ /usr/local/nginx

./nginx/sbin/nginx -t

./nginx/sbin/nginx

lsof -i :80


访问测试:


 wKioL1fDyKmgsncbAADz75XRCUY766.jpg


 

 

[root@lnmp nginx-1.6.2]# pwd
/usr/local/src/nginx-1.6.2
[root@lnmp nginx-1.6.2]# ./configure  --help|grep upstream
  --without-http_upstream_ip_hash_module
                                     disable ngx_http_upstream_ip_hash_module
  --without-http_upstream_least_conn_module
                                     disable ngx_http_upstream_least_conn_module
  --without-http_upstream_keepalive_module
                                     disable ngx_http_upstream_keepalive_module


此模块已经被安装了



配置

[root@nginx-proxy conf]# pwd
/usr/local/nginx/conf
[root@nginx-proxy conf]# egrep -v "#|^$" nginx.conf.default  >nginx.conf
复制模块文档的例子,粘贴修改一下
upstream backend {
    server 192.168.1.180:80 max_fails=3 fail_timeout=30s;
    server 192.168.1.181:80 max_fails=3 fail_timeout=30s;
}
    server {
        listen       80;
        server_name  www.test.com;
        index  index.html index.htm;
        location / {
           proxy_pass http://backend;
        }


实现原理(默认是轮询的算法)

 


保存重启

/usr/local/nginx/sbin/nginx -s reload

/usr/local/nginx/sbin/nginx -t


然后检查两个web服务是否正常,分别访问一下ip

最后地址输入负载均衡服务器IP,轮询那两个web服务器的访问的内容

或者

for n in `seq 100`;do curl 192.168.1.138;sleep 2;done
http://www.test.com
www.www.test.com
http://www.test.com
www.www.test.com
http://www.test.com
www.www.test.com
http://www.test.com



然后宕机期中一个,观察现象

会自动排除故障