This is kind of a weird complicated question. Context: I have a bunch of docker containers that need to be routed to from haproxy dynamically. They are each running on different ports on the machine, and are stored in environment variables like this:
a=9873
b=9874
c=9875
These are available to the haproxy server. The request path that comes in will be in the form like this example:
/api/a/action
From that, the taks is as follows:
The
/api
needs to be removed from the path.The
/a
refers to the service, so the environment variable fora
needs to be retrieved to get the port of the server- The request needs to be routed to
localhost:9873/a/action
where the port, 9873, is the environment variable that is the value from the path in the beginning (after removing/api
) and then the path is simply appended onto the request (which is the/a/action
that remains after removing the/api
.
My current config looks like this:
backend api
reqrep ^([^\ ]*\ /)api[/]?(.*) \1\2
server api_server localhost:9871
All this config is doing is removing the /api
from the path of the request and sending it to a static port, 9871. *I need this port to be the value held by the environment variable of the same name as the first element in the path (the /a
above) and the rest (passing the remaining path) is already working.*
I also would like to be able to get the environment variable of the name prefix_a
, where the path will have the name /a
, but I need to prepend one common prefix prefix_
to get the environment variable. This can be a separate question or search though, unless it's simple to just put that into the solution.
Please let me know if I can clarify or give more information that might help solve the problem.
(I've done a heck a lot of googling. Here are some related urls but not quite the answer I need:
- https://gist.github.com/meineerde/8bea63e64fc47f9a67c0
- Dynamic routing to backend based on context path in HAProxy How can I set up HAProxy to a backend based on a value in the url?
- Haproxy route and rewrite based on URI path
- haproxy: get the host name
- https://serverfault.com/questions/818937/haproxy-is-giving-me-problems-with-regex-replace-is-this-a-bug-or-am-i-doing-so
- https://serverfault.com/questions/668025/how-to-use-environment-variable-in-haproxy
- http://cbonte.github.io/haproxy-dconv/1.9/configuration.html#7.2
- How do I set a dynamic variable in HAProxy?
- use environment variables in haproxy