Versões utilizada: Debian 8.5(Jessie) + HAProxy 1.6 ou Debian 9.3(Stretch) + HAProxy 1.7
Avaliar Manager Haproxy https://github.com/hap-wi/roxy-wi
Baixar a versão atual do HAProxy
# apt-get update
# apt-get install haproxy hatop
Ajustar o repositório do Debian para baixar a versão 1.6 ou mais recente do HAProxy
# vi /etc/apt/sources.list
deb http://ftp.debian.org/debian jessie-backports main
# apt-get update
# apt-get install -t jessie-backports haproxy hatop
A configuração do arquivo hosts é para configurar o parâmetro bind *:80 do HAProxy para um valor diferente de por exemplo site1.domain.com:80. Esta condição server somente se não houver múltiplos sites.
Ajustar o arquivo /etc/hosts com o nome de todos os websites que passaram pelo HAProxy
# vi /etc/hosts
127.0.0.1 localhost
111.11.1.1 site1.domian.com site1
111.11.1.1 site2.domian.com site2
Verificando a versão instalada:
# haproxy -v
Configuração:
# cd /etc/haproxy/
# cp -a haproxy.cfg haproxy.cfg.default
# vi haproxy.cfg
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
#stats socket /run/haproxy/admin.sock mode 660 level admin
stats socket /run/haproxy/info.sock mode 666 level user
stats timeout 30s
user haproxy
group haproxy
daemon
maxconn 4096
# Default SSL material locations
ca-base /etc/ssl/certs
crt-base /etc/ssl/private
# Default ciphers to use on SSL-enabled listening sockets.
# For more information, see ciphers(1SSL). This list is from:
# https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
ssl-default-bind-options no-sslv3
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000
timeout client 50000
timeout server 50000
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
frontend www-http
ha
# BALANCER ######
backend www-backend
balance roundrobin <- leastconn,source,uri,url_param,hdr(name)
server <NAME01> <PRIV_IP_01>:80 check
server <NAME02> <PRIV_IP_02>:80 check
# REVESE PROXY #####
frontend site
bind *:9990
default_backend site-backend
backend site-backend
server <NAME> <PRIV_IP>:9990 check
Testar se o arquivo de configuração esta valido
# haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
Reinicie para validar as configurações
# /etc/init.d/haproxy restart
Para acesso com ssl é necessário configurar o haproxy para aceitar o certificado conforme abaixo:
frontend http-https
bind *:80
bind *:443 ssl crt /etc/haproxy/certs/site.pem
redirect scheme https if !{ ssl_fc }
reqadd X-Forwarded-Proto:\ https <- Força o redirecionamento http para https
use_backend WWW if { ssl_fc_sni www.domain.com }
backend WWW
server SRV01 1.1.5.3:8080 check
É possível deixar os arquivos .pem separados ou aninhar todos em um único .pem, abaixo é demonstrado com múltiplos ssl em um .pem.
bind *:443 ssl crt /etc/haproxy/certs/site1.pem crt /etc/haproxy/certs/site2.pem
Testar se o arquivo de configuração esta valido
# haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
Reinicie para validar as configurações
# /etc/init.d/haproxy restart
Onde o cenário externo tem um certificado válido emitido por um CA e internamente a aplicação tem um certificado auto assinado, é possível fazer by pass e permanecer com o certificado externo. As url's do certificado externo e interno devem ser os mesmos
### // HTTP ##################################
frontend HTTP
bind *:80
http-request add-header X-Forwarded-Proto http
# Redirecionamento para site https
redirect scheme https if { hdr(host) -i site.domain.com.br } !{ ssl_fc }
### // HTTPS ##################################
frontend HTTPS
bind *:443 ssl crt /etc/ssl/private/certificado.pem
http-request add-header X-Forwarded-Proto https
acl is_SSQL path -i /
acl SSQL hdr(host) -i site.domain.com.br
redirect code 301 location https://site.domain.com.br/path01/02/Login.aspx if SSQL is_SSQL
use_backend SQL if SSQL
backend SQL
server SQL1 <IP_SERVER>:443 check ssl verify none
Para validar url inserida no browser e direcionar ao servidor correto ajuste conforme um modo abaixo:
# vi haproxy.cfg
frontend HTTP
bind *:80
reqadd X-Forwarded-Proto:\ http <- Força trafego em http
# Caso exista algum redirecionamento para site https
redirect scheme https if { hdr(host) -i site1.com.br } !{ ssl_fc }
redirect scheme https if { hdr(host) -i www.site1.com.br } !{ ssl_fc }
redirect scheme https if { hdr(host) -i site02.com.br } !{ ssl_fc }
redirect scheme https if { hdr(host) -i www.site02.com.br } !{ ssl_fc }
## SITES HTTP ##################
acl WWW hdr(host) -i www.domain.com domain.com
use_backend WWW if WWW
acl WWW1 hdr(host) -i www.domain1.com domain1.com
option accept-invalid-http-request <- Aceita caracteres especiais na URL
use_backend WWW1 if WWW1
backend WWW
server SRV1 <IP>:80 check
backend WWW1
server SRV1 <IP>:8080 check
## SITES HTTPS #################
frontend HTTPS
bind *:443 ssl crt /etc/haproxy/certs/CERT-SITE01.pem crt /etc/haproxy/certs/CERT-SITE02.pem
reqadd X-Forwarded-Proto:\ https
acl WWW1 hdr(host) -i www.site01.com
use_backend WWW1 if WWW1
acl WWW2 hdr(host) -i www2.site02.com
acl WWW2-SUB path_beg -i /subspath
use_backend WWW2-SUB if WWW2-SUB
use_backend WWW2 if WWW2
backend WWW
server SRV1 <IP>:80 check
backend WWW2
server SRV1 <IP>:80 check
backend WWW2-SUB
server SRV1 <IP>:81 check
server SRV2 <IP>:81 check backup
Testar se o arquivo de configuração esta valido
# haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
Reinicie para validar as configurações
# /etc/init.d/haproxy restart
Para habilitar o modo de manutenção é necessário ter dois serves para redirecionamento. O HAProxy trata o resultado 404 de uma página não encontrada como em modo de manutenção, existindo um servidor secundário o redirecionamento de todo o fluxo é passado até que o servidor principal volte a apresentar código 200. Caso ocorra o código 503 de "Server Unavailable", o redirecionamento atua para que o sistema não fique indisponível.
Ajuste a configuração haproxy.conf
backend <NOME>
....
option httpchk
http-check disable-on-404
server SRV01 10.0.0.1:80 check
server SRV02 10.0.0.2:80 check backup
....
Para redirecinar de http://www.doamin.com para http://www.domain.com/path utilize:
acl is_SITE path -i /
acl SITE hdr(host) -i pep.domain.local
acl SITEHOM hdr(host) -i pephom.domain.local
redirect code 301 location http://site.domain.com/path if SITE is_SITE
redirect code 301 location http://sitehom.domain.com/path if SITEHOM is_SITE
use_backend PP if SITE
use_backend PPHM if SITEHOM
backend PP
balance source
server SITE1 <IP_SERVER>:80 check maxconn 100
server SITE2 <IP_SERVER>:80 check maxconn 100
backend PPHM
server SITEHOM <IP_SERVER>:80 check maxconn 100
Para redirecionar a URL de um site, é possível utilizar o HAProxy. No link/link tem a descrição de cada comando. A situação que precisa ser observada é onde deve ser dispostas as linhas de configuração, se antes ou depois da linha "reqadd X-Forwarded-Proto:\ https". O parametro http-request trabalha na camada de aplicação (7) e passa o SSL passa de forma transparente.
Ajuste a configuração haproxy.conf
Utilizando http-request é necessário configurar antes de reqadd
....
http-request redirect code 301 <location|prefix> http://site.destino.com.br if { hdr(host) -i origem.net.br }
http-request redirect code 301 <location|prefix> http://site.destino.com.br if { hdr(host) -i www.origem.net.br }
reqadd X-Forwarded-Proto:\ https
....
Para uso do serviço de proxypass, basta ajustar a configuração conforme abaixo:
...
frontend
bind *:80
use_backend SITE if { hdr(host) -i siteORIG.domain.com }
backend SITE
server WEB siteDEST.domain.com
...
Ajustar a configuração do haproxy.conf
frontend HTTP
bind *:80
use_backend stat if { path -i /stats }
backend stat
bind *:1936
stats hide-version
stats enable
stats uri /stats
stats refresh 30s
stats show-legends
stats show-node
stats auth admin:password
Para verificar o status do HAProxy acesse
http://<IP_SERVER>:1936
login: admin
senha: password
Também é possivel visualizar em modo texto através do comendo:
# apt-get install hatop
# hatop -s /run/haproxy/info.sock
Existe a possibilidade de configurar o serviço do HAProxy com multi-processamento bastando ajustar os campos abaixo, verifique a quantidade de processadores/cores
# nproc
4
Ou
# apt-get install lshw
# lshw -short -class cpu
H/W path Device Class Description
==================================================
/0/401 processor Intel(R) Xeon(R) CPU E5620 @ 2.40GHz
/0/402 processor Intel(R) Xeon(R) CPU E5620 @ 2.40GHz
/0/403 processor Intel(R) Xeon(R) CPU E5620 @ 2.40GHz
/0/404 processor Intel(R) Xeon(R) CPU E5620 @ 2.40GHz
Com o resultado dos comandos acima foi possivel constatar a quantidade de 4 CPU, agora basta ajustar o HAProxy para reconhecer e utilizar todos os CPU's
Ajustar a configuração do haproxy.conf
Config com ajustes de processador:
$ vi haproxy/haproxy.cfg
global
....
nbproc 4
cpu-map 1 0
cpu-map 2 1
cpu-map 3 2
cpu-map 4 3
stats bind-process 4
frontend HTTP
bind-process 1 2 3 4 <- Pode ser configurado no backend
....
Ajustes finos
defaults
....
option forwardfor
option http-server-close
##option http-keep-alive
option redispatch
option httpclose
option persist
cookie SERVERID insert indirect nocache
....
No Ubuntu 14.4 foi necessário configurar os parametros abaixo para o funcionamento
# vi /etc/sysctl.conf
net.unix.max_dgram_qlen=512
Reinicie os serviços
# service rsyslog restart
# service haproxy restart
É possível tratar mensagens 400/403/408/500/502/503/504 e exibir uma mensagem mais amigável.
No caminho /etc/haproxy/errors existem as mensagens padrão, altere conforme a necessidade.
Criar o arquivo /etc/haproxy/errors/503-fora_do_ar.http e alterar seu conteúdo:
# vi /etc/haproxy/errors/503-fora_do_ar.http
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=utf-8
<html>
<body>
<center><h1>Serviço não disponível</h1></center>
<center><h1>Sistema em manutenção</h1></center>
</body>
</html>
Ajustar o configuração do HAProxy
# vi haproxy.cfg
backend wiki
mode http
server SERV2 10.0.0.2:80 check
errorfile 503 /etc/haproxy/errors/503-fora_do_ar.http
Testar se o arquivo de configuração esta valido
# haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
Reinicie para validar as configurações
# /etc/init.d/haproxy restart
listen rtmp :1935 <-STREAMING mode tcp balance roundrobin server s1 xxx.xxx.xxx.xxx:1935 check server s2 xxx.xxx.xxx.xxx:1935 check
HAProxy+GEOIP
http://blog.haproxy.com/2012/07/02/use-geoip-database-within-haproxy/