Route by using existing cookie
Solution 1
For testing a specific server behind haproxy I can recommend this approach:
frontend http
acl is_cookie_hack_1 hdr_sub(cookie) server_test_hack=server1
acl is_cookie_hack_2 hdr_sub(cookie) server_test_hack=server2
... insert your normal acl rules here
use_backend bk_server_1 if is_cookie_hack_1
use_backend bk_server_2 if is_cookie_hack_2
... insert your normal use_backend expressions here
backend bk_server_1
...
backend bk_server_2
...
I insert the server_test_hack cookie by javascript in my browser's js console by this script:
document.cookie="server_test_hack=server1";
Solution 2
You can't use your existing cookie for balancing, the way you could use the URI parameter. You can't just take the md5() or build the hash table of the cookie, at least that is not documented. You could use prefix parameter for the cookie to achieve a different result. It might be what you are looking for (if you want to avoid creation of yet another cookie).
So in your case the config would look like this:
backend bk_web
balance roundrobin
cookie SESS prefix indirect nocache
server s1 192.168.10.11:80 check cookie s1
server s2 192.168.10.21:80 check cookie s2
When the request arrives without a cookie, any server is chosen by round-robin and request is redirected to it. When response arrives from the backend, HAProxy checks for the SESS cookie and if it's set, it prepends the server name (sX) to the cookie and sends it to the client. In the browser, the cookie looks like sX~, but when the next request is sent with that cookie, the backend server only sees in the cookie, as HAProxy strips the sX~ part
Source: load balancing, affinity, persistence, sticky sessions: what you need to know
Solution 3
If you just want to read cookies in the request and route accordingly, you can do something like this in your configuration:
frontend http
acl cookie_found hdr_sub(cookie) COOKIENAME
use_backend app_server if cookie_found
backend app_server
balance roundrobin
server channel1 X.X.X.X:PORT #Host1
server channel2 Y.Y.Y.Y:PORT #Host2
Related videos on Youtube
Era
Updated on September 16, 2022Comments
-
Era almost 2 years
How can I route requests in haproxy using a cookie that was set on the app servers?
Example:
SESS=<hash-of-username>
haproxy should not insert cookies by itself in any case.
-
Era over 10 yearsThat doesn't allow me to balance by using the cookie value, it only checks if a cookie is there.
-
Gooner over 10 yearsI have edited the "backend" configuration to add balancing. I'm not sure, if this is what you were looking for.
-
Era over 10 yearsNo, it still doesn't balance using the cookie value.
-
Donny V. over 9 years@ErikAigner make the cookie name the value your looking for.
-
marcostvz about 7 yearsI tested this solution and worked like a charm, thanks! :)
-
Sebi2020 about 3 yearsJust add multiple acls and use_backend statements to establish backend routing.