haproxy实现tcp代理 2016年07月29日 09:44:58 haproxy实现tcp代理

haproxy实现tcp代理

简介

haproxy大多数情况下在http(七层)代理,如apache,tomcat等,下面我们就来讲下haproxy的tcp(四层)代理,可以用于ssh、mysql、mongodb等多种场合。

需求

ip 应用 角色
10.10.10.15 haproxy tcp代理
10.10.10.16 mongodb master
10.10.10.17 mongodb slave

haproxy代理mongodb,实现主从读写分离。

安装

 unzip haproxy-1.6.4.zip 
 cd haproxy-1.6.4
 make TARGET=linux26 PREFIX=/usr/local/haproxy 
 make install PREFIX=/usr/local/haproxy
  • 1
  • 2
  • 3
  • 4

配置

1.添加haproxy用户并创建相关目录

useradd haproxy
mkdir -p /usr/local/haproxy/{etc,logs}
  • 1
  • 2

2.配置日志输出

vim /etc/rsyslog.conf
#haproxy
$ModLoad imudp
$UDPServerRun 514
local3.* /usr/local/haproxy/logs/haproxy.log

service rsyslog restart
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.配置文件

#
# demo config for Proxy mode
# 

global
        maxconn         20000 #最大连接数
    ulimit-n        204800  #ulimit的数量限制
        log             127.0.0.1 local3
        user             haproxy 
        group            haproxy
        chroot          /var/empty
    nbproc      4 #启动后运行的进程数量
        daemon #以后台形式运行haproxy
    pidfile     /var/run/haproxy.pid
defaults
    log global  
    mode tcp  #代理的级别(7层http,4层tcp)
    retries 3 #3次连接失败认为服务不可用,也可以在后面设置
    timeout connect 5s #连接超时
    timeout client 30s #客户端超时
    timeout server 30s #服务器端超时
    option redispatch  
    option          nolinger
    no option dontlognull
    option      tcplog
    option log-separate-errors


listen admin_stats  #监控页面设置
    bind 0.0.0.0:26000
    bind-process 1
    mode http
    log 127.0.0.1 local3 err
    stats refresh 30s ##每隔30秒自动刷新监控页面
    stats uri /haproxy_status
    stats realm welcome login\ Haproxy
    stats auth admin:admin
    stats hide-version
    stats admin if TRUE

frontend mongodb_read   #读代理
    bind        10.10.10.15:27000
    default_backend db_read


frontend mongodb_write  #写代理
    bind        10.10.10.15:27001
    default_backend db_write

backend db_read  #master slave都可以读
    balance roundrobin #负载均衡的方式,roundrobin是轮询
    server db1 10.10.10.16:27017 check inter 1500 rise 3 fall 3 weight 2
    #check inter 1500是检测心跳频率,rise 3是3次正确认为服务器可用,fall 3是3次失败认为服务器不可用,weight代表权重 
    server db2 10.10.10.17:27017 check inter 1500 rise 3 fall 3 weight 2

backend db_write #master 支持写
    server db1 10.10.10.16:27017
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

4.启动

/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/etc/haproxy.cfg
  • 1

日志格式分析

猜你喜欢

转载自blog.csdn.net/wangshuminjava/article/details/80226946
今日推荐