nginx配置负载均衡

  1. 首先创建三个linux环境,并且作为反向代理的服务必须能拼通那两个处理请求的服务
 
首先我们去lnmp环境下的里面找到nginx的配置文件。
在开始之前,我们可以先去配置一个虚拟域名
配置方法如下:
  1. 在nginx.config中加入,意思是把这个配置文件引入,注意路径。

  1. 然后编辑这个文件,把nginx.conf的server复制一份出来,进行编辑
 
server {
#端口号
listen 80;
#域名
server_name www.xing.com;
 
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
#这是然nginx解析php文件
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
 
  1. 然后在windows的hosts里面加入
Ip www.xing.com
 
  1. 然后重启nginx
/usr/local/nginx/sbin/nginx -s reload 各个系统重启不太一样,请自行百度
 
 
 
正式配置负载均衡
  1. 找到nginx.conf。
在http这个模块下加入连接池,例如
 
 
三种常用方法配置,还有其他,想知道,自行百度。
  1. 轮询
upstream xing {
server 10.101.87.77; #ip是你处理服务的ip
server 10.101.87.9; #ip是你处理服务的ip,可以多个
}
  1. 权重,权重就是开哪个服务器处理的请求多,例如下面,它的意思是加入有100个请求,ip1处理80个,ip2处理20个,也就是4/1的意思
upstream xing {
server 10.101.87.77 weight=80;
server 10.101.87.9 weight=20;
}
  1. ip哈希,是根据请求的ip进行分配,同一个ip它会访问一个ip
upstream xing {
ip_hash;
server 10.101.87.77;
server 10.101.87.9;
}
三种选择一种就好。完成后进入咱们配置好的a.conf里面去。
 
  1. 进入引入的那个文件,也就是咱们配置虚拟域名那。

我的是这个,你可以随便命名。
 
 
  1. 里面进行这样编辑,
 
server {
#端口
listen 80;
#域名
server_name www.xing.com;
 
#charset koi8-r;
 
#access_log logs/host.access.log main;
#这是分发请求的方法。
location / {
#这是加入一个服务器相应错误后,他会继续请求没问题的服务器
proxy_next_upstream http_502 http_504 error timeout invalid_header;
#这的xing要和你连接池的名字保持一致,他的意思把连接池里的ip替换到这来。
proxy_pass http://xing;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
 
#error_page 404 /404.html;
 
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
 
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
 
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#现在这个东西可以注释了。因为现在这个服务器我们只作为一个反向代理的服务器,并不需要解析文件。
# location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# include fastcgi_params;
#}
 
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
 
  1. 然后重启nginx
/usr/local/nginx/sbin/nginx -s reload
  1. 最后就简单了,把两个处理请求的服务器的根目录创建一个相同的文件,两个文件的内容按道理必须一样,在这里我们为区分我们的负载均衡是否成功,我们在两个文件中,输入不同的内容,然后开始访问,看他是否进行轮询。如果每次访问的服务器不总是一个,这就对了。

posted @ 2019-02-20 18:35  不二神探V  阅读(174)  评论(0编辑  收藏  举报