红联Linux门户
Linux帮助

Linux下Nginx反向代理实现负载均衡

发布时间:2015-03-19 09:58:29来源:linux网站作者:海底苍鹰

想配置一下Linux下Nginx的反向代理,用来实现负载均衡功能。各种原因耽误了,今天配置了一下,遇到了不少麻烦,但是还是搞定了。


一,先启动nginx和php-cgi

#启动 php-cgi
/usr/local/bin/spawn-fcgi -a 127.0.0.1 -p 8000 -C 5 -f /usr/bin/php-cgi

#启动 nginx
ulimit -SHn 65535
/usr/local/nginx/sbin/nginx


二,修改配置nginx.conf

upstream myselfx {
server 127.0.0.1:10002;
server 127.0.0.1:10001 weight=5;
}

server
{
listen       10000;
server_name  localhost;

log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
access_log  /var/log/apps.log  access;

location /
{
#     fastcgi_pass  127.0.0.1:8000;
#     fastcgi_index index.php;
proxy_pass http://myselfx;
proxy_redirect                      off;
proxy_set_header   Host             $host;
proxy_set_header   X-Real-IP        $remote_addr;
proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
client_max_body_size       100m;
client_body_buffer_size    256k;
proxy_connect_timeout     60;
proxy_send_timeout         30;
proxy_read_timeout         30;
proxy_buffer_size          8k;
proxy_buffers              8 64k;
proxy_busy_buffers_size    64k;
proxy_temp_file_write_size 64k;
}

location /NginxStatus
{
stub_status on;
auth_basic "NginxStatus";
auth_basic_user_file /usr/local/nginx/conf/authfile;
}
}

说明:

1,我用一台电脑实现这个负载均衡的,用10000反向代理10001,10002

2,反向代理不要php-cgi支持,所以在上面的配置中没有index和root这类的东西

3,proxy_pass http://myselfx;这里的http://一定要有不然报错,upstream myselfx这前面一定不要有http://,不然也会报错,不知道为什么非要这样配置

4,开始的时候 proxy_pass http://127.0.0.1:10000; upstream 127.0.0.1:10000;我这样配置的,nginx不报错,但是我只要一访问http://localhost:10000/这个url时,log文件很快就达到147.7M,好大。里面全部是127.0.0.1这样的数字。这一点根apache,haproxy的思想不太一样。这个也浪费我了好多时间。

5,proxy_pass http://myselfx;里面的myselfx没有任何意义,在这里只是起个标识作用,在访问页面的时候,是http://localhost:10000/,而不是http://myselfx

6,你要看清楚你用的是proxy_pass而不是fastcgi_pass,开始老是报错,就是因为我用的是fastcgi_pass

7,access_log的位置要放在proxy_pass所在location的前面,不然不会启作用

8, location /NginxStatus 这一块是查看nginx的状态 ,htpasswd -cbd /usr/local/nginx/conf/authfile 用户名  密码

9,stub_status on;这个要开启,表示允许查看nginx的状态,如果不开启,你输入了authfile里面的用户名和密码了,也看不到东西,会报403错误

10,weight=5,表示分配的权重,是一种算法,还有其他的如ip_hash,url_hash等。