Nginx做爲互聯網最經常使用的web服務器,高性能的HTTP和反向代理使它常常做爲Tomcat集羣的方案。Nginx官方只支持使用HTTP協議的集成,可是若是你想使用AJP協議集成,能夠使用阿里開源的nginx_ajp_module。接下來咱們使用HTTP的方式集成:html
1.準備Nginx、Tomcat一、Tomcat2nginx
Nginx下載並啓動:http://nginx.org/en/download.htmlweb
nginx默認端口80,我這裏爲了方便也就不修改了,直接啓動apache
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.43tomcat
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/spa
2.配置Nginx,將Nginx與Tomcat一、Tomcat2集成3d
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/,不斷刷新