Mastering Nginx

(Ron) #1

NGINX as a Reverse Proxy


[ 74 ]

Keepalive connections

The keepalive directive deserves special mention. NGINX will keep this number of


connections per worker open to an upstream server. This connection cache is useful


in situations where NGINX has to constantly maintain a certain number of open
connections to an upstream server. If the upstream server speaks HTTP, NGINX


can use the HTTP/1.1 Persistent Connections mechanism for maintaining these
open connections.


upstream apache {

server 127.0.0.1:8080;

keepalive 32;

}

location / {

proxy_http_version 1.1;

proxy_set_header Connection "";

proxy_pass http://apache;

}

Here, we've indicated that we'd like to hold open 32 connections to Apache running


on port 8080 of the localhost. NGINX need only negotiate the TCP handshake for


the initial 32 connections per worker, and will then keep these connections open by
not sending a Connection header with the close token. With proxy_http_version,


we specify that we'd like to speak HTTP/1.1 with the upstream server. We also clear
the contents of the Connection header with proxy_set_header, so that we are not


proxying the client connection properties directly.


If more than 32 connections are needed, NGINX will, of course, open them to


satisfy requests. After this peak has passed, NGINX will close the least recently


used connections, to bring the number back down to 32, as we indicated in the
keepalive directive.


This mechanism can also be used to proxy non-HTTP connections, as well. In the


following example, we show that NGINX maintains 64 connections to two instances


of memcached:

Free download pdf