Linux环境Nginx反向代理实现负载均衡
上一篇简单介绍了Nginx的安装及启停操作(Linux环境Nginx安装),本篇我们将启动两个Tomcat Server,然后通过Nginx实现负载均衡配置。
1、tomcat下载
下载地址:https://downloads.apache.org/tomcat/tomcat-8/v8.5.64/bin/apache-tomcat-8.5.64.tar.gz
下载之后在服务器103,104上进行解压,解压目录/opt/develop/apache-tomcat-8.5.64
2、tomcat启动
2.1 进入/opt/develop/apache-tomcat-8.5.64/webapps目录,新建一个test项目
2.2 在test项目下新建一个test.html文件,文件内容为:《I am 103!》
同理,在另一台Tomcat Server下执行以上相同操作,test.html文件内容为:《I am 104!》
2.3 进入bin目录启动tomcat
/opt/develop/apache-tomcat-8.5.64/bin/startup.sh
2.4 访问test.html
在浏览器中输入http://172.16.43.103:8080/test/test.html,http://172.16.43.104:8080/test/test.html。查看tomcat是否可以正常访问。
3、Nginx配置
修改/usr/local/nginx/nginx.conf文件,Nginx安装参考:Linux环境Nginx安装
在http节点下增加,nginx默认采用按请求时间轮询策略,其它负载均衡策略可以参考这篇:https://zhuanlan.zhihu.com/p/131031963
upstream web_servers { server 172.16.43.103:8080; server 172.16.43.104:8080; }
在server节点下增加,记得将原来默认的location /{}配置注释掉。
location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://web_servers; }
nginx.conf配置如下:
#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; upstream web_servers { server 172.16.43.103:8080; server 172.16.43.104:8080; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; #location / { # root html; # index index.html index.htm; #} location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://web_servers; } }
配置修改完毕,重新加载nginx
[root@test1 sbin]# ./nginx -s reload
在浏览器中输入http://172.16.43.103/test/test.html
多刷新两次可以看到,我们的访问地址不管,但是返回的内容会发生变化,说明已经通过nginx实现了负载均衡,能够正常访问到两台Tomcat Server。