nginx upstream keepalive connections
Nginx從 1.1.4 開始,實(shí)現(xiàn)了對后端機(jī)器的長連接支持,這是一個(gè)激動(dòng)人心的改進(jìn),這意味著 Nginx 與后端機(jī)器的通信效率更高,后端機(jī)器的負(fù)擔(dān)更低。
例如,對一個(gè)沒有長連接支持的后端機(jī)器,會出現(xiàn)大量TIME_WAIT 狀態(tài)的連接,使用以下命令驗(yàn)證之:
netstat -n | grep TIME_WAIT
經(jīng)過查閱官方文檔,其目前已經(jīng)實(shí)現(xiàn)了http, fastcgi, memcache 協(xié)議的長連接支持。而之前的版本中僅支持memcache 協(xié)議。
1. 啟用到 memcache 服務(wù)器的長連接
在upstream 配置段中增加 keepalive N 指令即可:
upstream memcached_backend {
server 127.0.0.1:11211;
server 10.0.0.2:11211;
keepalive 32;
}
server {
...
location /memcached/ {
set $memcached_key $uri;
memcached_pass memcached_backend;
}
}
2. 啟用fastcgi 長連接支持
除了需要在upstream 中配置 keepalive N 外,還需要在 location 中增加 fastcgi_keep_conn on;
upstream fastcgi_backend {
server 127.0.0.1:9000;
keepalive 8;
}
server {
...
location /fastcgi/ {
fastcgi_pass fastcgi_backend;
fastcgi_keep_conn on;
...
}
}
3. 啟用對后端機(jī)器HTTP 長連接支持
upstream http_backend {
server 127.0.0.1:8080;
keepalive 16;
}
server {
...
location /http/ {
proxy_pass http://http_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
...
}
}
注意:需要設(shè)置nginx 代理請求的 http 協(xié)議版本號為 1.1, 以及清除掉 Connection 請求header, 官方文檔描述:
For HTTP, the proxy_http_version directive should be set to “ 1.1 ” and the “Connection ” header field should be cleared .
The connections parameter should be set low enough to allow upstream servers to process additional new incoming connections as well.
即是說:keepalive N 指令中 , N 的值應(yīng)該盡可能設(shè)置小一些,以便后端機(jī)器可以同時(shí)接受新的連接。
在我負(fù)責(zé)的生產(chǎn)環(huán)境中,前端是nginx, 靜態(tài)文件緩存使用 varnish, 使用長連接之后, varnish機(jī)器的連接數(shù)從 8000 多下降至 200 多,負(fù)載值也有明顯降低。
但是針對fastcgi, 即后端機(jī)器是 php-fpm 服務(wù)時(shí),在 nginx 日志中出現(xiàn)以下錯(cuò)誤:
upstream sent unsupported FastCGI protocol version: 0 while reading upstream 。
廣泛搜集,目前還未解決之。如果您遇到同樣的問題并解決之,請一定聯(lián)系筆者信箱zhangxugg@163.com, 甚是感謝。