HAProxy as a static reverse proxy for Docker containers
I like Docker. A lot.
Everything I build and deploy now ends up in their own container on some server/VPS of mine. One reason for this is because of how easy it is to move the site or service to another server if needed. Just export and import the Docker container and you’re done. No config on web and database servers needed, it’s all done.
But there’s one thing you need to do. You can’t have lots of containers listening on the same public port 80, so you have to have your containers listening on some random port like 4553, 4566, 4333 etc. But your site’s visitors are coming to port 80 so you need to somehow listen to port 80 and forward requests to the right Docker container on the right port.
There are several ways to do this and I started out with Nginx as a reverse proxy. This works fine but I don’t want a web server doing that. I’ve used HAProxy in the past for load balancing. And it is actually just what I need, a load balancer is made for forwarding requests.
So here’s how you use it as a reverse proxy for your docker containers.
Install HAProxy (Debian)
sudo apt-get install haproxy
Edit config file
sudo nano /etc/haproxy.cfg
//Put this in the file
global
daemon
maxconn 4096
defaults
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend http-in
bind *:80
acl is_site1 hdr_end(host) -i domain1.se
acl is_site2 hdr_end(host) -i domain2.com
use_backend site1 if is_site1
use_backend site2 if is_site2
backend site1
balance roundrobin
option httpclose
option forwardfor
server s2 127.0.0.1:49153 maxconn 32
backend site2
balance roundrobin
option httpclose
option forwardfor
server s1 127.0.0.1:2082 maxconn 32
listen admin
bind 127.0.0.1:8080
stats enable
Start/Restart HAProxy
sudo /usr/sbin/haproxy -f /etc/haproxy.cfg -D -p /var/run/haproxy.pid
There are lots more stuff you can do with HAProxy but this is a basic forwarding proxy.
The only downside with this is that it’s static and any change in ports needs to manually be updated in HAProxy config file.
EDIT
I’ve created a post on how you can automate this with Nginx config files, Nginx as a reverse proxy in front of your docker containers >>