Autopilot_Pattern_Haproxy - acehippo/slowmotion GitHub Wiki

build haproxy with autopilot pattern

  • install consul-template & containerpilot on Dockerfile
# Use consul-template to re-write haproxy config
RUN curl -Lo /tmp/consul_template_0.15.0_linux_amd64.zip https://releases.hashicorp.com/consul-template/0.15.0/consul-template_0.15.0_linux_amd64.zip && \
    unzip /tmp/consul_template_0.15.0_linux_amd64.zip && \
    mv consul-template /bin

# Get ContainerPilot release
ENV CONTAINERPILOT_VERSION 2.4.1
RUN export CP_SHA1=198d96c8d7bfafb1ab6df96653c29701510b833c && \
    curl -Lso /tmp/containerpilot.tar.gz "https://github.com/joyent/containerpilot/releases/download/${CONTAINERPILOT_VERSION}/containerpilot-${CONTAINERPILOT_VERSION}.tar.gz" && \
    echo "${CP_SHA1}  /tmp/containerpilot.tar.gz" | sha1sum -c && \
    tar zxf /tmp/containerpilot.tar.gz -C /bin && \
    rm /tmp/containerpilot.tar.gz

COPY containerpilot.json /etc/
ENV CONTAINERPILOT=file:///etc/containerpilot.json
  • containerpilot.json
{
  "consul": "{{ .CONSUL_ADDR }}",
  "preStart": "/bin/reload.sh preStart",
  "logging": {
    "level": "DEBUG",
    "format": "text"
  },
  "services": [
    {
      "name": "haproxy",
      "port": 80,
      "tags": ["{{ .APIGW_ENV }}"],
      "health": "/usr/bin/curl -o /dev/null --fail -s http://localhost",
      "interfaces": ["eth1", "eth0"],
      "poll": 10,
      "ttl": 25
    }
  ],
  "backends": [
    {
      "name": "apigw",
      "poll": 10,
      "onChange": "/bin/reload.sh onChange"
    }
  ]
}
  • reload.sh
#!/bin/bash

preStart() {
    echo "preStart"
    consul-template -once -consul $CONSUL_ADDR \
        -template "/etc/containerpilot/haproxy.cfg.ctmpl:/usr/local/etc/haproxy/haproxy.cfg"
}

onChange() {
    echo "onChange"
    consul-template -once -consul $CONSUL_ADDR \
        -template "/etc/containerpilot/haproxy.cfg.ctmpl:/usr/local/etc/haproxy/haproxy.cfg:kill -HUP $(pidof haproxy-systemd-wrapper)"
}

until
    cmd=$1
    if [ -z "$cmd" ]; then
        onChange
    fi
    shift 1
    $cmd "$@"
    [ "$?" -ne 127 ]
do
    onChange
    exit
done
  • haproxy.cfg.ctmpl
global
  # daemon
  maxconn 2048
  tune.ssl.default-dh-param 2048

defaults
  mode http
  timeout connect 5000ms
  timeout client 50000ms
  timeout server 50000ms

frontend https-in
  bind 0.0.0.0:80
  bind 0.0.0.0:443 ssl crt /usr/local/etc/haproxy/haproxy.pem

  acl host_trident_consul hdr(host) -i trident-consul-{{ env "APIGW_ENV" }}.cloudpi.net
  use_backend trident-consul if host_trident_consul

  default_backend servers

# {{ env "APIGW_ENV" }}
backend servers{{ range printf "%s.apigw" (env "APIGW_ENV") | service }}
  server neptune-api {{ .Address }}:{{ .Port }} check maxconn 256{{ end }}

backend trident-consul
  server trident-consul {{ env "CONSUL_ADDR" }} check maxconn 256