当前位置 主页 > 服务器问题 > Linux/apache问题 >
什么是负载均衡?
当一个域名指向多台web服务器时,添加一台nginx负载均衡服务器,通过nginx负载均衡即可将来自于客户端的请求均衡的发送给每台web服务器,避免单台服务器负载过高而其余服务器较为空闲的不均衡情况出现
配置nginx负载均衡:
在nginx机器上新建配置文件:
[root@centos02 ~]# vi /etc/nginx/conf.d/test.conf
添加如下内容:
upstream test { ip_hash; server 192.168.0.10:80 weight=100; server 192.168.0.20:80 weight=50; } server { listen 80; server_name www.test.com; location / { proxy_pass http://test; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }upstream:负载均衡配置 test:自定义名,用于server{}中proxy_pass引用 ip_hash:将同一客户端的所有请求发送给同一服务器(如不发送给同一服务器,有可能出现客户端刚登陆网站,点击其他子页面又提示登陆) server:web服务器地址 weight:定义权重(范围0-100),负载均衡服务器优先将请求发送给权重大的web服务器(以上示例如果有150条请求进来,192.168.0.10会被分配100条,192.168.0.20会被分配50条) server_name:访问网站的域名 proxy_pass:引用upstream定义的名称
验证nginx配置并重载:
[root@centos02 ~]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@centos02 ~]# nginx -s reload
接下来修改客户端hosts文件将测试的域名www.test.com指向到测试的nginx负载均衡机器的IP即可访问www.test.com网站。
负载均衡配置示例补充
1.根据请求的文件配置:
upstream aa { server 192.168.0.10; server 192.168.0.20; } upstream bb { server 192.168.0.100; server 192.168.0.101; } server { listen 80; server_name www.test.com; location ~ aa.php { proxy_pass http://aa/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~ bb.php { proxy_pass http://bb/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { proxy_pass http://bb/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
请求aa.php的,会到aa组,请求bb.php的会到bb组,其他请求全部到bb组,必须要有location / {} ,否则不能正确匹配url
2.根据请求的目录配置:
upstream aa { server 192.168.0.10; server 192.168.0.20; } upstream bb { server 192.168.0.100; server 192.168.0.101; } server { listen 80; server_name www.test.com; location /dir1/ { proxy_pass http://aa/dir1/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /dir2/ { proxy_pass http://bb/dir2/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { proxy_pass http://bb/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }