安装HAProxy 如果想安装最新版则跳过懒人安装使用脚本安装
yum install -y haproxy # CentOS
或
apt-get install -y haproxy # Ubuntu
删除原来的配置文件再新建一个新的,方便快捷 /etc/haproxy/haproxy.cfg:
rm -rf /etc/haproxy/haproxy.cfg
vi /etc/haproxy/haproxy.cfg
或者
nano /etc/haproxy/haproxy.cfg
#---------------------------------------------------------------------
# 全局配置
#---------------------------------------------------------------------
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 50000
user haproxy
group haproxy
daemon
nbthread 4
#---------------------------------------------------------------------
# 默认配置
#---------------------------------------------------------------------
defaults
mode tcp
log global
option dontlognull
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
retries 3
option redispatch
#---------------------------------------------------------------------
# 统计页面配置
#---------------------------------------------------------------------
listen stats
bind *:9999
mode http
stats enable
stats uri /stats
stats refresh 15s
stats auth admin:admin123
stats hide-version
stats show-desc "HAProxy监控统计"
# 自定义页面处理
http-request return file /etc/haproxy/html/stats.html content-type "text/html" if { path / }
#---------------------------------------------------------------------
# 端口转发配置
#---------------------------------------------------------------------
frontend port_range_12001_12003
bind *:12001-12003
mode tcp
maxconn 20000
# ========== 合并的 stick-table(兼容旧版本语法)==========
stick-table type ip size 1m expire 30s store conn_rate(10s),conn_cur,gpc0
# ========== 连接跟踪 ==========
tcp-request connection track-sc0 src
# ========== CC 防护规则 ==========
# 定义 ACL(基于连接数和频率)
acl too_many_conn sc0_conn_cur ge 5 # 并发连接数 ≥ 5
acl too_fast_conn sc0_conn_rate ge 10 # 连接速率 ≥ 10次/10秒
# 触发 CC 规则时增加计数器
tcp-request connection sc-inc-gpc0(0) if too_many_conn || too_fast_conn
# 检查黑名单(gpc0 计数器 > 0)
acl banned sc_get_gpc0(0) gt 0
# 拒绝非法连接
tcp-request connection reject if banned
tcp-request connection reject if too_many_conn || too_fast_conn
default_backend remote_servers
#---------------------------------------------------------------------
# 后端服务器配置
#---------------------------------------------------------------------
backend remote_servers
balance static-rr
server server_12001 192.168.1.2:12001 check inter 2000 rise 2 fall 3
server server_12002 192.168.1.2:12002 check inter 2000 rise 2 fall 3
server server_12003 192.168.1.2:12003 check inter 2000 rise 2 fall 3
需要注意:
确保本地防火墙开放对应端口
确保有足够的系统资源处理连接
建议先在测试环境验证配置
将监控页面改成中文显示
mkdir -p /etc/haproxy/html
cat > /etc/haproxy/html/stats.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
<title>HAProxy监控面板</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 12px 8px; text-align: left; }
th { background-color: #4CAF50; color: white; }
tr:nth-child(even) { background-color: #f9f9f9; }
.status-UP, .status-正常 { color: #4CAF50; font-weight: bold; }
.status-DOWN, .status-离线 { color: #f44336; font-weight: bold; }
.refresh { margin: 20px 0; }
h1 { color: #333; text-align: center; margin-bottom: 30px; }
button { padding: 8px 16px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #45a049; }
</style>
<script>
function loadStats() {
fetch('/stats;csv')
.then(response => response.text())
.then(data => {
const rows = data.split('\n');
const headers = rows[0].split(',');
// 只显示重要的列
const importantColumns = [
'pxname', 'svname', 'scur', 'smax', 'stot',
'status', 'check_status', 'lastchg', 'check_desc'
];
// 中文表头映射
const headerMap = {
'pxname': '代理名称',
'svname': '服务器名称',
'scur': '当前连接数',
'smax': '最大连接数',
'stot': '总连接数',
'status': '状态',
'check_status': '检查状态',
'lastchg': '最后变更(秒)',
'check_desc': '检查描述'
};
// 创建表头
let html = '<table><tr>';
importantColumns.forEach(col => {
const colIndex = headers.indexOf(col);
if (colIndex !== -1) {
html += `<th>${headerMap[col] || col}</th>`;
}
});
html += '</tr>';
// 添加数据行
for(let i = 1; i < rows.length; i++) {
if(rows[i].trim() === '') continue;
const cols = rows[i].split(',');
html += '<tr>';
importantColumns.forEach(col => {
const colIndex = headers.indexOf(col);
if (colIndex !== -1) {
let value = cols[colIndex];
if(col === 'status') {
const statusClass = value === 'UP' ? 'status-UP' : 'status-DOWN';
value = value === 'UP' ? '正常' : '离线';
html += `<td class="${statusClass}">${value}</td>`;
} else if(col === 'lastchg') {
// 转换秒数为可读格式
const seconds = parseInt(value);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if(days > 0) {
html += `<td>${days}天</td>`;
} else if(hours > 0) {
html += `<td>${hours}小时</td>`;
} else if(minutes > 0) {
html += `<td>${minutes}分钟</td>`;
} else {
html += `<td>${seconds}秒</td>`;
}
} else {
html += `<td>${value}</td>`;
}
}
});
html += '</tr>';
}
html += '</table>';
document.getElementById('stats').innerHTML = html;
});
}
// 每5秒刷新一次
setInterval(loadStats, 5000);
loadStats();
</script>
</head>
<body>
<div class="container">
<h1>HAProxy监控面板</h1>
<div class="refresh">
<button onclick="loadStats()">刷新数据</button>
<span>(每5秒自动刷新)</span>
</div>
<div id="stats"></div>
</div>
</body>
</html>
EOF
启动服务
systemctl start haproxy
创建一个简单的管理脚本(方便操作):
#!/bin/bash
# 保存为 haproxy-manage.sh
CONFIG_FILE="/etc/haproxy/haproxy.cfg"
# 检查配置
check_config() {
haproxy -c -f $CONFIG_FILE
}
# 重载配置
reload_config() {
systemctl reload haproxy
}
case "$1" in
"check")
check_config
;;
"reload")
check_config && reload_config
;;
"status")
systemctl status haproxy
;;
*)
echo "使用方法: $0 {check|reload|status}"
;;
esac
给脚本执行权限
chmod +x haproxy-manage.sh
检查配置
./haproxy-manage.sh check
重载配置(不影响现有连接)
./haproxy-manage.sh reload
查看状态
./haproxy-manage.sh status
评论 (0)