1: 我们把项目部署在两台服务器上,在hosts文件里面配置域名解析
2: 配置nginx服务器的负载均衡
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
#====================== 我们这里自定义负载均衡 =====================
server {
# 监听80端口
listen 80;
server_name www.wulei.com;
location / {
# 用来获取nginx的真实ip
proxy_set_header X-Real_IP $remote_addr;
proxy_pass http://myservers;
}
}
upstream myservers{
# ip_hash负载均衡策略:
ip_hash;
# 服务器地址
server 192.168.5.6:8081;
server 192.168.5.5:8081;
}
}
测试:
==========================================================
nginx负载均衡策略:
1. ip_hash 策略:每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
2. 默认轮询策略:
upstream myservers{
server 192.168.5.6:8081;
server 192.168.5.5:8081;
}
3. 权重策略:指定轮询几率,weight和访问比率成正比
upstream myservers{
server 192.168.5.6:8081 weight=9;
server 192.168.5.5:8081weight=2;
}
4. fiar策略(第三方):按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream myservers{
server 192.168.5.6:8081;
server 192.168.5.5:8081;
fair;
}