21 Nisan 2015 Salı

Haproxy Transparent Mode on Centos 7

Haproxy Transparent Mode on Centos 7

 HAProxy can’t do transparent binding or proxying alone. It must stand on a compiled and tuned Linux Kernel and operating system.
But Centos 7 supported haproxy transparent mode.
Step by step configuration; 
1. sysctl settings
2. iptables rules
3. ip route rules
4. HAProxy configuration

Step 1 is Sysctl serttings;
 – net.ipv4.ip_forward
  – net.ipv4.ip_nonlocal_bind
# echo 1 > /proc/sys/net/ipv4/ip_forward
# echo 1 > /proc/sys/net/ipv4/ip_nonlocal_bind

Step 2 is iptables rules;
#iptables -F -t mangle
#iptables -F
#iptables -F -t nat
#iptables -t mangle -N DIVERT
#iptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
#iptables -t mangle -A DIVERT -j MARK --set-mark 1

#iptables -t mangle -A DIVERT -j ACCEPT

Step 3 is ip route rules;
tell the Operating System to forward packets marked by iptables to the loopback where HAProxy can catch them:
#ip rule add fwmark 1 lookup 100

#ip route add local 0.0.0.0/0 dev lo table 100

Step 4 is haproxy configuration;
Finally, you can configure HAProxy.
  * Transparent binding can be configured like this:
frontend App_in
        bind ipofhaproxy:10421 transparent

        mode tcp

backend App_out
        mode tcp
        log global
        source 0.0.0.0 usesrc clientip
        balance roundrobin
        server backend1 ipofbackend01:10421 check
        server backend2 ipofbackend02:10421 check

Note: When you reboot the server ,ip rules will be delete.
Bash script will help you ;)
#!/bin/bash
iptables -F
iptables -F -t nat
iptables -t mangle -N DIVERT
iptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
iptables -t mangle -A DIVERT -j MARK --set-mark 1
iptables -t mangle -A DIVERT -j ACCEPT
ip rule add fwmark 1 lookup 100
ip route add local 0.0.0.0/0 dev lo table 100