Haproxy maps

Haproxy is one of the best reverse proxy servers out there (saying that after year of using it for various personal and work related projects … some quite creative I’d say … ) and when I heard about its “maps” functionality (combined with the admin socket and the hitless reload functionality) I immediately realised that one can “play” with web traffic while it is happening and do so without clients feeling anything.

This stuff is not new (bleeding edge) but seeing as how various ppl that I interact with are not familiar with it I decided to write a piece on my blog about it so that they have something to start with when they decide to explore the depths of haproxy.

The concept of a map for haproxy means having a simple text file that contains one pair per line in the form “url backend” – see sample below:

# A comment begins with a hash sign
static.example.com  be_static
www.example.com     be_static
# You can add additional comments, but they must be on a new line
example.com         be_static
api.example.com     be_api

In haproxy config file you’ll need to define something like this to get it working:

frontend frontendname       
   bind :80       
   use_backend %[req.hdr(host),lower,map(/etc/haproxy/maps/map.txt,defaultbackendname)]             

AND remember to have the backends defined in your haproxy config file (haproxy will load the map and the daemon will start ok BUT when traffic is directed to the non-existing backend it will be met with 500 errors 🙂 )

So the use_backend line above is a bit special this time … rather than specifying one backend to use based on some acl or simply using it statically now you’re actually telling it to use a backend for the host that’s being accessed relative to a map (text file) AND if it does not find an entry for it in the map file you’re telling it to use that defaultbackendname that you have .

This might not be much when you first look at it but now consider the following: the map can be altered at runtime by using the admin socket and even if you don’t want to do something like that you can simply edit the file and reload haproxy (customers will not feel this operation provided you’re using haproxy > 1.8 and ideally a kernel >= 4.x) … combine that with your need to shift traffic from one backend to another because of reasons (ddos, maintenance, etc) and it suddenly becomes really really useful to know and have.

A more detailed explanation for haproxy maps can be found here:
https://www.haproxy.com/blog/introduction-to-haproxy-maps/ and ofc in the manual.

Enjoy! 🙂


Posted

in

by