...
ONe of my main reasons for moving to HAProxy was to enable HTTP session management at as little cost as possible. The following is a description of how to enable this in HAProxy.
If you want web sessions to have persistent connections to the same server, you can use a balance
algorithm such as
hdr, rdp-cookie, source, uri, orurl_param.
If your implementation requires the use of the
leastconn
,roundrobin
, orstatic-rr
algorithm,
you can implement session persistence by using server-dependent cookies.
To enable session persistence for all pages on a web server, use the cookie
directive to define the name of the cookie to be inserted and add the cookie
option and server name to the server
lines, for example:
Code Block | ||
---|---|---|
| ||
cookie WEBSVR insert server websvr1 192.168.1.71:80 weight 1 maxconn 512 cookie 1 check server websvr2 192.168.1.72:80 weight 1 maxconn 512 cookie 2 check |
HAProxy includes an additional Set-Cookie:
header that identifies the web server in its response to the client, for example: Set-Cookie: WEBSVR=
. If a client subsequently specifies the N
; path=page_path
WEBSVR
cookie in a request, HAProxy forwards the request to the web server whose server cookie
value matches the value of WEBSVR
.
The following example demonstrates how an inserted cookie ensures session persistence:
$ while true; do curl http://10.0.0.10; sleep 1; done
This is HTTP server websvr1 (192.168.1.71).
This is HTTP server websvr2 (192.168.1.72).
This is HTTP server websvr1 (192.168.1.71).
^C
$ curl http://10.0.0.10 -D /dev/stdout
HTTP/1.1 200 OK
Date: ...
Server: Apache/2.4.6 ()
Last-Modified: ...
ETag: "26-5125afd089491"
Accept-Ranges: bytes
Content-Length: 38
Content-Type: text/html; charset=UTF-8
Set-Cookie: WEBSVR=2; path=/
This is HTTP server svr2 (192.168.1.72).
$ while true; do curl http://10.0.0.10 --cookie "WEBSVR=2;"; sleep 1; done
This is HTTP server websvr2 (192.168.1.72).
This is HTTP server websvr2 (192.168.1.72).
This is HTTP server websvr2 (192.168.1.72).
^C