负载均衡是我们大流量网站要做的一个东西,下面我来给大家介绍在Nginx服务器上进行负载均衡配置方法,希望对有需要的同学有所帮助哦。
负载均衡
先来简单了解一下什么是负载均衡,单从字面上的意思来理解就可以解释N台服务器平均分担负载,不会因为某台服务器负载高宕机而某台服务器闲置的情况。那么负载均衡的前提就是要有多台服务器才能实现,也就是两台以上即可。
测试环境:
测试域名:test.ikang.com
A服务器IP:192.168.1.39
B服务器IP:192.168.1.52
部署思路:
A服务器做主服务器,域名直接解析到A服务器(192.168.1.39)上,由A服务器负载均衡到B服务器(192.168.1.52)上.
域名解析:
在hosts文件末尾添加 test.ikang.com
安装Nginx:
首先安装依赖包:
yum install -y httpd-devel pcre perl pcre-devel zlib zlib-devel GeoIP GeoIP-devel openssl*1.下载nginx安装包
2.[iyunv@redis opt]# tar -xvf nginx-1.4.0.tar.gz
3.[iyunv@redis nginx-1.4.0]#./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
4.make
5.make install
nginx.conf文件配置:
vi /usr/local/nginx/conf/nginx.conf
在http段加入以下代码:
upstream test.ikang.com {
server 192.168.1.39:8083 weight=5;
server 192.168.1.52:8083 weight=5;
}
server {
listen 80;
server_name test.ikang.com;
location / {
#root html;
#index index.html index.htm;
proxy_pass http://test.ikang.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
保存重启nginx
测试:
打开浏览器访问test.ikang.com结果,刷新会发现所有的请求均分别被主服务器(192.168.1.39)分配到B服务器(192.168.1.52)上,实现了负载均衡效果。
这时你打开浏览器输入test.ikang.com可以看到39和52浏览器的页面交替出现,那就证明是成功了。
最后:
一、负载均衡不是nginx独有,著名鼎鼎的apache也有,但性能可能不如nginx。
二、多台服务器提供服务,但域名只解析到主服务器,而真正的服务器IP不会被ping下即可获得,增加一定安全性。
三、upstream里的IP不一定是内网,外网IP也可以。不过经典的案例是,局域网中某台IP暴露在外网下,域名直接解析到此IP。然后又这台主服务器转发到内网服务器IP中。 四、某台服务器宕机、不会影响网站正常运行,Nginx不会把请求转发到已宕机的IP上
|