Nginx作為互聯網最常用的web服務器,高性能的HTTP和反向代理使它經常作為Tomcat集群的方案。Nginx官方只支持使用HTTP協議的集成,但是如果你想使用AJP協議集成,可以使用阿里開源的nginx_ajp_module。接下來我們使用HTTP的方式集成:
1.准備Nginx、Tomcat1、Tomcat2
Nginx下載並啟動:http://nginx.org/en/download.html
nginx默認端口80,我這里為了方便也就不修改了,直接啟動
server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
Tomcat下載並啟動:https://tomcat.apache.org/download-80.cgi#8.5.43
tomcat由於是同一台機器,我這里修改了端口號,配置分別是:
<Server port="8005" shutdown="SHUTDOWN">
<Connector port="8081" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<Server port="8006" shutdown="SHUTDOWN"> <Connector port="8082" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8444" /> <Connector port="8010" protocol="AJP/1.3" redirectPort="8444" />
修改好配置,把示列工程sample1放在tomcat1,sample2放在tomcat2里面,啟動兩個tomcat:
訪問http://localhost:8081/sample1/
訪問http://localhost:8082/sample2/
2.配置Nginx,將Nginx與Tomcat1、Tomcat2集成
Nginx集成可以使用HTTP方式,也可以使用AJP方式,這里使用的HTTP方式。
2.1修改nginx的目錄下conf下nginx.conf配置
在http{}下面配置
#配置服務器1 upstream sample1{ server localhost:8081; } #配置服務器2 upstream sample2{ server localhost:8082; }
在server{}下配置
#映射服務器1 location /sample1/ { proxy_pass http://sample1; } #映射服務器2 location /sample2/ { proxy_pass http://sample2; }
重啟nginx,再一次訪問
http://localhost/sample1/
http://localhost/sample2/
3.負載均衡配置
在http{}下面配置
#負載均衡配置服務器群組 upstream sample1{ #實例1 server localhost:8081 weight=1 max_fails=3 fail_timeout=30s; #實例2 server localhost:8082 weight=1 max_fails=3 fail_timeout=30s; }
在server{}下配置
#映射服務器集群 location /sample1/{ proxy_pass http://sample1; }
因為這里我們配置的兩個項目是不同名稱的,所以負載均和1:1時候,會有一個是無法訪問。
在tomcat2里面把tomcat1里面的sample1復制過來,顯示改為hello,tomcat2!
訪問http://localhost/sample1/,不斷刷新