Skip to content

Instantly share code, notes, and snippets.

@voxxit
Last active September 27, 2020 17:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voxxit/229668c0466b840e8e8e816bc9ed9ec5 to your computer and use it in GitHub Desktop.
Save voxxit/229668c0466b840e8e8e816bc9ed9ec5 to your computer and use it in GitHub Desktop.

Consul-backed HAProxy Load Balancer

To build & run direct from this Gist, run the following commands:

docker build -t consul-haproxy https://gist.github.com/229668c0466b840e8e8e816bc9ed9ec5.git
docker run --rm -it -p 9000:9000 -p 8000:8000 consul-haproxy
How it works

This uses the demo.consul.io nyc3 Consul cluster, which has web service with multiple nodes attached. If/when nodes are added/removed, or any of the Consul template values change, the load balancer is automatically reloaded gracefully with the new values using consul-template by sending haproxy a SIGHUP kill signal.

FROM haproxy:1.7
ENV CT_VERS=0.16.0 \
CONSUL_HTTP_ADDR=demo.consul.io
RUN apt-get update \
&& apt-get -y install --no-install-recommends curl ca-certificates unzip \
&& curl -O https://releases.hashicorp.com/consul-template/${CT_VERS}/consul-template_${CT_VERS}_linux_amd64.zip \
&& unzip consul-template_${CT_VERS}_linux_amd64.zip \
&& mv consul-template /usr/local/bin/ \
&& apt-get -y remove --purge curl ca-certificates unzip \
&& apt-get -y autoremove --purge \
&& rm -rf consul* /var/lib/apt/lists/*
COPY haproxy.cfg.tmpl /usr/local/src/
COPY start.sh /usr/local/bin/
CMD ["/usr/local/bin/start.sh"]
global
daemon
maxconn {{key "service/haproxy/maxconn"}}
defaults
mode {{key "service/haproxy/mode"}}{{range ls "service/haproxy/timeouts"}}
timeout {{.Key}} {{.Value}}{{end}}
listen stats
bind *:9000
stats uri /haproxy_stats
stats realm HAProxy\ Statistics
stats auth access:secret
stats admin if TRUE
listen http-in
bind *:8000{{range service "web"}}
server {{.Node}} {{.Address}}:{{.Port}}{{end}}
#!/bin/bash
[ -z $CONSUL_HTTP_ADDR ] && echo "Consul HTTP address is required" && exit 1
exec consul-template \
-template "/usr/local/src/haproxy.cfg.tmpl:/usr/local/etc/haproxy/haproxy.cfg" \
-exec "./docker-entrypoint.sh haproxy -f /usr/local/etc/haproxy/haproxy.cfg"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment