轉載自:http://hi.baidu.com/gnaiqeh/blog/item/c8024c11bfeacff2c2ce79f4.html
關鍵詞:nginx tomcat 多虛擬主機 集群 負載均衡
雖然夜深了,但是還是解決了這個困擾我一個晚上的問題,記錄下來備查。
接著我前不久寫的這一篇來的:Linux下nginx和tomcat的整合http://hi.baidu.com/gnaiqeh/blog/item/2f43dac9e98d781a7f3e6fc7.html
舉個例子,現在是這樣的情況:我現在有a、b、c三個不同的應用,每個Tomcat集群機(一共3個)上都建立了這三個應用的虛擬主機,我要把這三個應用用一個nginx來負載均衡。
中間測試了很多次,失敗的過程就不多說了,直接說最終解決的辦法。
首先要把3個虛擬主機的域名(a.gnaiqeh.cn、b.gnaiqeh.cn、c.gnaiqeh.cn)都指向到nginx機的公網ip上。
然后還是修改nginx的配置文件nginx.conf:
配置文件中upstream段還是保持不變,依舊是3個tomcat集群機的地址及負載因子:
upstream gnaiqeh {
server 192.168.0.11:8080 weight=1;
server 192.168.0.12:8080 weight=1;
server 192.168.0.13:8080 weight=1;
}
因為有3個應用,所以應該有3個server段,這里只寫其中一個,其他兩個只需要修改一下server_name即可:
server {
listen 80;
server_name a.gnaiqeh.cn; #另外兩個是b.gnaiqeh.cn、c.gnaiqeh.cn
location / {
root html;
index index.jsp index.html index.htm;
proxy_redirect off;
proxy_set_header Host $host; #這一句至關重要
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://gnaiqeh;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
proxy_set_header是nginx的http代理模塊中的一個指令。
在nginx中的默認proxy是只能對后面real server做端口轉發的,而不能做域名轉發,即默認的是:
proxy_set_header Host $proxy_host;
我們要通過域名轉發就必須改為:
proxy_set_header Host $host;
最后修改tomcat的配置文件server.xml,主要是配置虛擬主機:
<Host name="a.gnaiqeh.cn" appBase="webapps-a"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<Context path="" docBase="/mnt/a" reloadable="true" crossContext="true"/>
</Host>
<Host name="b.gnaiqeh.cn" appBase="webapps-b"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<Context path="" docBase="/mnt/b" reloadable="true" crossContext="true"/>
</Host>
<Host name="c.gnaiqeh.cn" appBase="webapps-c"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<Context path="" docBase="/mnt/c" reloadable="true" crossContext="true"/>
</Host>
3臺集群機均改成上面一樣的。
然后重啟nginx,重啟tomcat,測試訪問三個域名都通過,打完收工。