最近在部署服务时,遇到这样一个问题,有3台服务器(比如 172.168.0.1----172.168.0.3,这三台是相互连通的)其中172.168.0.1对应的公网地址为210.188.133.109,其它服务外网均不能直接访问。现在要求web服务部署在172.168.0.1也即210.188.133.109。在172.168.0.3上安装mysql。那么外网怎么直接访问安装在172.168.0.3服务器上的数据库呢?这个时候可以用haproxy作代理解决。
一、haproxy安装
yum install -y haproxy
二、haproxy配置
vim /etc/haproxy/haproxy.cfg
#内容如下,listen mysql 与 listen redis为自己添加
# Example configuration for a possible web application. See the
# full configuration options online.
# http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
# to have these messages end up in /var/log/haproxy.log you will
# need to:
#
# 1) configure syslog to accept network log events. This is done
# by adding the '-r' option to the SYSLOGD_OPTIONS in
# /etc/sysconfig/syslog
#
# 2) configure local2 events to go to the /var/log/haproxy.log
# file. A line like the following can be added to
# /etc/sysconfig/syslog
# local2.* /var/log/haproxy.log
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
listen mysql
bind 0.0.0.0:7306
mode tcp
balance roundrobin
server mysql1 172.168.0.3:3306
# server mysql2 172.168.0.6:3306
listen redis
bind 0.0.0.0:7379
mode tcp
balance roundrobin
server redis1 172.168.0.3:6379
其中,7306,6379为代理的接口。
三、日志配置
CentOS 7上yum安装的Haproxy,默认没有记录日志。需要做一下配置才能记录日志
3.1.创建日志文件/var/log/haproxy/haproxy.log
cd /var/log
mkdir haproxy
cd haproxy
touch haproxy.log
chmod a+w haproxy.log
3.2.开启rsyslog的haproxy日志记录功能
编辑vim /etc/rsyslog.conf文件,将
$ModLoad imudp
$UDPServerRun 514
两行前的#去掉。
在 local7.* /var/log/boot.log
之后添加
# Save haproxy log
local2.* /var/log/haproxy/haproxy.log
修改vim /etc/sysconfig/rsyslog 文件,将
SYSLOGD_OPTIONS=""
改为 SYSLOGD_OPTIONS="-r -m 2 -c 2"
3.3.重启rsyslog和haproxy服务,haproxy就能记录日志了。
systemctl restart rsyslog
systemctl restart haproxy
四.测试
通过navicat和redisDesktopManager工具测试