nginx+tocmat 負載均衡時,一臺tomcat宕機時的問題
在windows下作nginx負載均衡測試。
我的nginx的配置文件如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
upstream localhost {
server 127.0.0.1:8080 max_fails=2 fail_timeout=30s;
server 127.0.0.1:8081 max_fails=2 fail_timeout=30s;
}
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location /{
proxy_pass http://localhost;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
問題描述如下:
用了nginx負載均衡後,在兩臺tomcat正常運行的情況下,訪問http://localhost 速度非常迅速,通過測試程序也可以看出是得到的負載均衡的效果,但是我們試驗性的把其中一臺tomcat(server localhost:8080)關閉後,再查看http://localhost,發現反應呈現了一半反映時間快,一半反映時間非常非常慢的情況,但是最 後都能得到正確結果。
然後我又把關閉的那吧tomcat實例恢復,此時再訪問http://localhost,又可以很快的訪問,負載均衡也運行正常了!鬱悶!
分析懷疑可能是nginx將一半的左右的請求仍然發到了宕掉的tomcat實例上了,然後由於轉發到宕掉的tomcat沒有反映,nginx又重新分發到其它實例上處理。
但是這個時間也太長了。當有一臺宕機後,訪問http://localhost有時候會現了大概30s左右的響應時間,非常鬱悶!
那麼怎麼樣可以提高nginx對於宕掉的服務器的反應與處理,以使以後的請求到來不會還將期發送到原來宕掉的服務器。
問題解決:
server {
listen 80;
server_name localhost;
location /{
proxy_pass http://localhost;
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_connect_timeout 1;
proxy_read_timeout 1;
proxy_send_timeout 1;
}
}
或者
upstream localhost {
server 127.0.0.1:8080 max_fails=2 fail_timeout=1s;
server 127.0.0.1:8081 max_fails=2 fail_timeout=1s;
}
均可縮短連接超時時間!