user187676
user187676

Reputation:

Route by using existing cookie

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.

Upvotes: 7

Views: 16776

Answers (3)

arkod
arkod

Reputation: 2063

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";

Upvotes: 11

Xeos
Xeos

Reputation: 6487

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

Upvotes: 4

Gooner
Gooner

Reputation: 1590

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

Upvotes: 2

Related Questions