HTTP Loadbalance com HAProxy e Keepalived no Red Hat/CentOS
Autor: Fábio Fernandes Falcão | Publicado: 2009-12-10T13:41:00-03:00

A seguir estão os passos para instalação e configuração dos serviços HAProxy e Keepalived que farão toda a mágica do HTTP Loadbalance.Instalação do Keepalived, responsável pelo endereço Ip Virtual que receberá as requisições dos clientes:1- Instalar o kernel-devel referente ao seu kernel em uso2- Faça o download da versão mais atual do Keepalived em http://www.keepalived.org/download.html e copie na pasta /usr/src.cd /usr/srctar xzpvf keepalived-*.*.**.tar.gzcd keepalived-*.*.**./configure; makemake installln -s /usr/local/sbin/keepalived /usr/sbin/keepalivedln -s /usr/local/etc/sysconfig/keepalived /etc/sysconfig/keepalivedln -s /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf3- Conteúdo dos arquivos de configuração e script de inicialização do keepalived:/etc/keepalived/keepalived.confvrrp_script chk_haproxy {           # Requires keepalived-1.1.13    script "killall -0 haproxy"     # cheaper than pidof    interval 2                      # check every 2 seconds    weight 2                        # add 2 points of prio if OK}global_defs {notification_email {       admin@dominio.com}smtp_server 127.0.0.1lvs_id ServerA}vrrp_instance virtual {interface eth0state MASTERvirtual_router_id 39priority 110virtual_ipaddress {       10.1.50.36 #Endereço IP Virtual}track_script {      chk_haproxy}}/etc/sysconfig/keepalivedKEEPALIVED_OPTIONS="-D"/etc/init.d/keepalived#!/bin/sh## Startup script for the Keepalived daemon## processname: keepalived# pidfile: /var/run/keepalived.pid# config: /etc/keepalived/keepalived.conf# chkconfig: - 21 79# description: Start and stop Keepalived# Source function library. /etc/rc.d/init.d/functions# Source configuration file (we set KEEPALIVED_OPTIONS there). /etc/sysconfig/keepalivedRETVAL=0prog="keepalived"start() {echo -n $"Starting $prog: "daemon keepalived  --oknodo ${KEEPALIVED_OPTIONS}RETVAL=$?echo[ $RETVAL -eq 0 ] &amp;&amp; touch /var/lock/subsys/$prog}stop() {echo -n $"Stopping $prog: "killproc keepalivedRETVAL=$?echo[ $RETVAL -eq 0 ] &amp;&amp; rm -f /var/lock/subsys/$prog}reload() {echo -n $"Reloading $prog: "killproc keepalived -1RETVAL=$?echo}# See how we were called.case "$1" instart)       start    ;;stop)       stop    ;;reload)       reload    ;;restart)       stop       start    ;;condrestart)       if [ -f /var/lock/subsys/$prog ]; then              stop              start       fi    ;;status)       status keepalived    ;;*)       echo "Usage: $0                    {start|stop|reload|restart|condrestart|status}"    exit 1esacexit $RETVAL4- Ajuste de inicialização dos serviços nos respectivos Runlevels:chkconfig --add keepalivedchkconfig --level 2345 keepalived onOK. Keepalived Instalado e configurado corretamente.Agora partiremos para a instalação do HAProxy e alguns ajustes para que o mesmo funcione na mesma porta em que o apache está rodando, no caso de estarem rodando na mesma máquina:1- Faça o download do pacote RPM do HAProxy em http://rpm.pbone.net/index.php3/stat/4/idpl/6806415/com/haproxy-1.3.14.3-1.i586.rpm.html e instale na máquina:rpm -hiv haproxy-*.*.**.rpm2- Conteúdo do arquivo de configuração do HAProxy:/etc/haproxy/haproxy.cfg# haproxy.cfg file examplegloballog 127.0.0.1 local0 errlog 127.0.0.1 local1 noticemaxconn 4096user haproxygroup haproxydefaultslog globalmode httpoption httplogoption dontlognullretries 3option redispatch #redispatchmaxconn 2000contimeout 5000clitimeout 50000srvtimeout 50000listen webfarm 10.1.50.36:80mode httpstats enablestats auth someuser:somepasswordbalance roundrobincookie JSESSIONIDoption httpcloseoption forwardforoption httpchk HEAD /server-statusserver webA 10.1.50.38:80 cookie A checkserver webB 10.1.50.39:80 cookie B check3- Ajuste do syslog para logging do HAProxy:/etc/sysconfig/syslogSYSLOGD_OPTIONS="-m 0 -r"/etc/syslog.conf# Log Haproxylocal0.*                        /var/log/haproxy.loglocal1.*                        /var/log/haproxy.logOK. HAProxy Instalado e configurado corretamente.Falta agora ajustar o apache para escutar apenas no seu endereço ip principal, modificando apenas a linha abaixo no arquivo de configuração principal do Apache2:Onde está:Listen 80Modificar para:Listen 10.1.50.38:80Para acessar a página de estatísticas do HAProxy basta acessar o link http://endereço_ip_virtual/haproxy?statsPronto! Seus servidores estão configurados com os serviços de Keepalived, HAProxy, servindo páginas do Apache2 e sendo balanceados pelo HAProxy utilizando o endereço ip virtual do serviço Keepalived.Enjoy.