Nginx负载均衡的分发方式有4种: 1.轮询,默认采取此方式,Nginx会按照请求时间的先后顺序进行轮询分发,若某台Web Server宕机,Nginx自动将其摘掉。 2.weight,权重,即轮询的几率,默认为1,值越大,被分发的可能性越大,用于后端服务器性能不均的情况。 3.ip_hash,每个请求按访问ip的hash结果分配(注意一定要Nginx当做前端而且后端IP固定,不然没法确保一个ip请求落到同样的web机器) PS:一般解决Session都是用的memcache共享 4.自定义规则
upstream test.phpfs.com {
#ip_hash;
server 10.200.11.213:8081 down;
server 10.200.11.213:8082 weight=5;
server 10.200.11.215:8082 weight=5;
server 10.200.11.215:8081;
server 10.200.11.215:80 backup;
}
说明:test.phpfs.com只是为了起一个名字 down 表示当前的Web Server暂时不参与负载 weight 默认为1.weight越大,负载的权重就越大。 backup:其它所有的非backup Server down或者忙的时候,请求backup机器。所以这台机器压力会最轻。 场景 机器A:10.200.11.215 机器B:10.200.11.213 A开启80,8081,8082提供web服务,模拟三台Web服务器 B开启80作为分发机,8081,8082作为另外两台Web服务器 这样的相当于后端有5台机器提供web服务! A机器80站点根目录/home/80(备用机,暂时不提供服务) A机器8081站点根目录/home/8081(权重是1) A机器8082站点根目录/home/8082(权重是5) B机器8081站点根目录/home/8081(不提供服务) B机器8082站点根目录/home/8082(权重是5) PHP-FPM监听/var/run/php5-fpm.sock 配置10.200.11.213机器 /etc/nginx/conf.d/ 80.conf 存放存放负载配置 配置如下:
#upstream
upstream test {
#ip_hash;
server 10.200.11.213:8081 down;
server 10.200.11.213:8082 weight=5;
server 10.200.11.215:8082 weight=5;
server 10.200.11.215:8081;
server 10.200.11.215:80 backup;
}
server {
listen 80;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering off;#disabled cache
proxy_pass http://test;
}
}
8081.conf 存放8081端口网站
server {
listen 8081;
root /home/8081;
index index.php index.html index.htm;
server_name test.phpfs.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
8082.conf 存放8082端口网站
server {
listen 8082;
root /home/8082;
index index.php index.html index.htm;
server_name test.phpfs.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
配置10.200.11.215机器 /etc/nginx/conf.d/ 80.conf 存放80端口网站
server {
listen 80;
root /home/80;
index index.php index.html index.htm;
server_name test.phpfs.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
8081.conf 存放8081端口网站
server {
listen 8081;
root /home/8081;
index index.php index.html index.htm;
server_name test.phpfs.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
8082.conf 存放8082端口网站
server {
listen 8082;
root /home/8082;
index index.php index.html index.htm;
server_name test.phpfs.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
测试域名:test.phpfs.com 绑定host:10.200.11.213 test.phpfs.com