Using HAproxy to and LXC containers

Does anybody have an idea or link that explains how I gain access to LXC containers via haproxy installed on the same host. I don’t want to install haproxy in a container.

Put the container IP address as one of the servers ?

I attempted that that, but it didn’t work. With Docker I used port redirecting.

If you are using an LXD managed bridge on the host, then each container can be assigned a static IP which you can then use in your HAProxy config to connect to. Remember to ensure that any services inside the container are listening on all IPs not just local loopback.

Why does it not work? Each container has a private ip address 10.x.x.x, which you use as a backend server address. There is nothing tricky to it. You need to pass on the original ip address of the client to the server, so it can log it properly, but that is a standard haproxy technique.

Why don’t you want to install hapropxy in a container?

I use haproxy in an alpine container, so it takes very little disk space. By doing this:

  • I can use the {container}.lxd as the server address, instead of the numeric ip, so it works even if the container changes ip (though it would need a restart of haproxy).
  • The usual advantages of using containers: isolation, snapshot, rollback, replace the haproxy container with another haproxy container, moving the haproxy container to another host, etc.

I forward each incoming port (typically 80 and 443) from the host to the haproxy container. I do this via shorewall, which is an iptables configurator. This requires learning how to use shorewall, but I have a template that I use for this, starting with the 2-interfaces example. I just need to figure out which is the external host interface (net) for each host. I always use the default internal interface (loc), lxdbr0. Shorewall also allows me to map a different public ssh port for each container, and possibly services other than http and https. I tried mapping ports with an LXD network device instead of shorewall, but then I lose the client’s ip address. It seems ugly, as it is implemented with a separate process for each port.

Finally got it to work using haproxy within a container. The issue was that I hadn’t used the LXD extension in the haproxy.cfg file.