Wednesday, July 08 2009 @ 11:14 AM CDT
Contributed by: nat
Views: 106
Apache 2.2's load balancer is pretty neat. However, to get persistence to work properly, you have to be careful. Here we are setting the balancer manager to watch a client cookie called BALANCEID, and each member has a particular route string tied to it that is set in the cookie. It's important to note that the cookie format must be: something.routestring, ie, nat.server1. If it is justserver1, it will not work.
Now there's the issue of the client cookie being set. What if you are load balancing a third party app or webserver and can't easily get the cookie set on the client? No problem! While it didn't work in 2.2.3 (in particular, the BALANCER_ROUTE_CHANGED var being set), when I tried in 2.2.11, I was able to set the cookie myself based on which balancer member was selected:
# Set session cookie if BALANCER_ROUTE_CHANGED, containing BALANCER_WORKER_ROUTE env variable, which is set to the route above
# Note that cookie value should be a session id, followed by a period, followed by the route.
# Since session id cookie usually not advised to be mutable, best create own cookie with anything you want
# for the session part, just make sure to have a period and route part last
### Used for setting cookie
LoadModule headers_module modules/mod_headers.so
Header add Set-Cookie "BALANCEID=balancer.%{BALANCER_WORKER_ROUTE}e; path=/;" env=BALANCER_ROUTE_CHANGED
# Just give some debug info in the header, don't use once you have it working
Header add X-Var "BALANCER_ROUTE_CHANGED=%{BALANCER_ROUTE_CHANGED}e" env=BALANCER_ROUTE_CHANGED
Header add X-Var "BALANCER_WORKER_ROUTE=%{BALANCER_WORKER_ROUTE}e" env=BALANCER_WORKER_ROUTE
Header add X-Var "BALANCER_SESSION_ROUTE=%{BALANCER_SESSION_ROUTE}e" env=BALANCER_SESSION_ROUTE
Presto! Session persistence, all handled at the reverse proxy load balancer level.