nginx负载均衡

负载均衡配置动静分离

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。

nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。

但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。

Http Proxy模块,功能很多,最常用的是proxy_passproxy_cache

如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:

./configure --add-module=../ngx_cache_purge-1.0 ......

nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内

在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:

upstream idfsoft.com {
  ip_hash;
  server 127.0.0.1:9080 weight=5;
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}

注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。

定义好upstream后,需要在server段内添加如下内容:

server {
  location / {
    proxy_pass http://idfsoft.com;
  }
}

实验环境

主机名 ip 服务
lb 192.168.100.123 lnmp
R1 192.168.100.77 httpd
R2 192.168.100.88 nginx

部署lnmp

lnmp的部署

部署httpd
请查看 httpd

部署nginx
请查看nginx

//nginx的关闭防火墙
[root@R2 nginx-1.20.1]# setenforce 0
[root@R2 nginx-1.20.1]# systemctl stop firewalld
//关闭httpd的防火墙
[root@R1 htdocs]# systemctl stop firewalld
[root@R1 htdocs]# setenforce 0

//关闭lnmp的防火墙
[root@lb ~]# systemctl stop firewalld
[root@lb ~]# setenforce 0

配置nginx主机的nginx配置文件
[root@R2 ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;    //把下面两行删掉,
            index  index.html index.htm;
        }

        location / {
            proxy_pass http://html;  //删除之后,添加这一行。
        }



//在server上面添加下面四行
    upstream html {
    server 192.168.100.77;
    }
    upstream php {
    server 192.168.100.123;
    } 

//把下面的注释取消
        location ~ \.php$ {
            proxy_pass   http://php;  //更改这一行。
        }


[root@R2 ~]# nginx -s reload

添加静态资源

[root@R1 ~]# cd /usr/local/apache/htdocs/
[root@R1 htdocs]# echo 'zdj' > index.html 

nginx负载均衡_第1张图片
nginx负载均衡_第2张图片

你可能感兴趣的:(部署,nginx)