Skip to content

Instantly share code, notes, and snippets.

@foxel
Last active January 23, 2019 11:50
Show Gist options
  • Save foxel/696dafb9a893b6a5c553b19c4c7390c8 to your computer and use it in GitHub Desktop.
Save foxel/696dafb9a893b6a5c553b19c4c7390c8 to your computer and use it in GitHub Desktop.
Haproxy + docker-gen hostname routing

What is this?

This gist includes config for haproxy + docker-gen system with routing http requests to different containers based on hostname label.

pre requirements

Usage

  • put haproxy.tmpl to /etc/haproxy/haproxy.tmpl and docker-gen.cfg to /etc/docker-gen.cfg
  • run docker-gen -config /etc/docker-gen.cfg to start the system
  • run containers with hostname label e.g. docker run --label hostname=foo.example.com nginx

Integrating with debian services

  • put docker-gen.service to /etc/systemd/system/docker-gen.service
  • enable service with systemctl enable docker-gen
  • start docker-gen service with service docker-gen start
[[config]]
template = "/etc/haproxy/haproxy.tmpl"
dest = "/etc/haproxy/haproxy.cfg"
IncludeStopped = true
onlyexposed = true
notifycmd = "service haproxy reload"
watch = true
wait = "2s:10s"
[Unit]
Description=A file generator that renders templates using Docker Container meta-data.
Documentation=https://github.com/jwilder/docker-gen
After=network.target docker.socket
Requires=docker.socket
[Service]
ExecStart=/usr/local/bin/docker-gen -config /etc/docker-gen.cfg
[Install]
WantedBy=multi-user.target
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
user haproxy
group haproxy
daemon
#maxconn 256
defaults
log global
mode http
option httplog
option dontlognull
contimeout 5000
clitimeout 5000
srvtimeout 15000
balance leastconn
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
option forwardfor header X-Real-IP
{{ $services := groupByLabel $ "hostname" }}
frontend http-in
bind *:80
#default_backend failback
{{ range $host, $containers := $services }}
{{ $name := replace $host "." "_" -1}}
acl host_{{ $name }} hdr_dom(host) -i {{ $host }}
use_backend {{ $name }} if host_{{ $name }}
{{ end }}
{{ range $host, $containers := $services }}
{{ $name := replace $host "." "_" -1}}
backend {{ $name }}
#option httpchk /ping.php
option http-server-close
{{ range $index, $container := $containers }}
{{ with $address := index $container.Networks 0 }}
server server{{ $index }} {{ $address.IP }}:80 check inter 10000 maxconn 50
{{ end }}
{{ end }}
{{ end }}
backend failback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment