NGINX+TOMCAT搭建高效能負載均衡叢集 配置方法
一、 工具
nginx
apache-tomcat
二、 目標
實現高效能負載均衡的Tomcat叢集:
三、 步驟
1、首先下載Nginx,要下載穩定版:
2、然後解壓兩個Tomcat,分別命名為apache-tomcat-6-1 和 apache-tomcat-6-2
3、修改 兩個Tomcat的啟動埠,分別為 8081 和 8082 —— 開啟Tomcat的conf目錄下的server.xml
4、多個 tomcat 伺服器 同時 指定到 相同 資源
5、配置Nginx來實現負載均衡了,只需要配置好Nginx的配置檔案即可 —— 開啟Nginx的conf目錄下的 nginx.conf
worker_processes 1;#工作程序的個數,一般與計算機的cpu核數一致 events { worker_connections 1024;#單個程序最大連線數(最大連線數=連線數*程序數) } http { include mime.types; #副檔名與檔案型別對映表 default_type application/octet-stream;#預設檔案型別 sendfile on;#開啟高效檔案傳輸模式,sendfile指令指定nginx是否呼叫sendfile函式來輸出檔案,對於普通應用設為 on,如果用來進行下載等應用磁碟IO重負載應用,可設定為off,以平衡磁碟與網路I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。 keepalive_timeout 65; #長連線超時時間,單位是秒 gzip on;#啟用Gizp壓縮 #伺服器的叢集 upstream 123.131.131.158 { #伺服器叢集名字 server 192.168.202.98:8081 weight=1;#伺服器配置 weight是權重的意思,權重越大,分配的概率越大。 server 192.168.202.98:8082 weight=2; } #當前的Nginx的配置 server { listen 8088;#監聽80埠,可以改成其他埠 (請求為 localhost:8088,則交給 123.131.131.158 的伺服器叢集處理) server_name localhost;############## 當前服務的域名 location / { proxy_pass http://123.131.131.158; #伺服器叢集名字 proxy_redirect default; proxy_set_header Host $host:$server_port; //非80埠 ,用80埠時 不需要$server_port proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; //解決getScheme,isSecure,sendRedirect } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
註解: 在代理模式下,Tomcat 如何識別使用者的直接請求(URL、IP、https還是http )?
在透明代理下,如果不做任何配置Tomcat 認為所有的請求都是 Nginx 發出來的,這樣會導致如下的錯誤結果:
request.getScheme() //總是 http,而不是實際的http或https
request.isSecure() //總是false(因為總是http)
request.getRemoteAddr() //總是 nginx 請求的 IP,而不是使用者的IP
request.getRequestURL() //總是 nginx 請求的URL 而不是使用者實際請求的 URL
request.getServerName //總是nginx請求的ip
request.getServerPort //總是nginx請求的埠
response.sendRedirect( 相對url ) //總是重定向到 http 上 (因為認為當前是 http 請求)
解決方式: 需要分別配置一下 Nginx 和 Tomcat
proxy_set_header Host $host:$server_port; //解決getRequestURL、getServerName、getServerPort
//nginx預設是80服務,否則需要 Host $host:$server_port,不配置servlet_port會導致丟失埠
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; //解決getScheme,isSecure,sendRedirect
配置Tomcat server.xml 的 Engine 模組下配置一個 Value:
<Engine name="Catalina" defaultHost="localhost">
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="X-Forwarded-For"
protocolHeader="X-Forwarded-Proto"
protocolHeaderHttpsValue="https" httpsServerPort="7001"/><!--非80埠時,不然request.getServerPort()方法返回 443 -->
配置雙方的 X-Forwarded-Proto 就是為了正確地識別實際使用者發出的協議是 http 還是 https。
X-Forwarded-For 是為了獲得實際使用者的 IP。
6、同時啟動 tomcat 伺服器,並 啟動Nginx ,訪問 地址