准备
准备3台服务器,并且互相可以ping通
demo1: 192.168.3.80
demo2: 192.168.3.81
demo3: 192.168.3.82
安装Nginx
参考Nginx的安装,为以上3台服务器都安装上
Nginx配置
让demo1作为负载服务器,访问demo1的请求,通过nginx转发到demo1和demo2,这里采用的是ip_hash策略。
代码语言:txt复制ip_hash是根据用户请求过来的ip,然后映射成hash值,然后分配到一个特定的服务器里面;使用ip_hash这种负载均衡以后,可以保证用户的每一次会话都只会发送到同一台特定的Tomcat里面,它的session不会跨到其他的tomcat里面去的;
user www www;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#access_log logs/access.log main;
#access_log "pipe:rollback logs/access_log interval=1d baknum=7 maxsize=2G" main;
sendfile on;
keepalive_timeout 65;
#gzip on;
upstream local_test {
ip_hash;
server 192.168.3.81:80 weight=10 max_fails=2 fail_timeout=60s;
server 192.168.3.82:80 weight=10 max_fails=2 fail_timeout=60s;
#check interval=3000 rise=2 fall=5 timeout=1000 type=http;
#check_keepalive_requests 100;
#check_http_send "GET / HTTP/1.0rnrn";
#check_http_expect_alive http_2xx http_3xx;
}
server{
listen 80;
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header S-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://local_test;
}
}
}
修改完Nginx的配置,重启
检验
为了方便查看效果,在3台服务器上,我都做了如下修改
代码语言:txt复制vim /usr/local/nginx/html/index.html
来显示每台服务器的ip
代码语言:txt复制demo1的ip:192.168.3.80
demo2的ip:192.168.3.81,
demo3的ip:192.168.3.82,
通过浏览器访问 192.168.3.80,如果转发到demo2或者demo3,显示出他们的ip,则配置成功