使用 HAProxy 进行 MySQL 负载均衡

本章教程主要记录如何用HAProxy 实现MySQL负载均衡配置。

一、安装haproxy

在 Ubuntu/Debian 上:

bash 复制代码
sudo apt-get update
sudo apt-get install haproxy

在 CentOS/RHEL 上:

bash 复制代码
sudo yum install haproxy

二、配置haproxy

编辑 HAProxy 配置文件(通常位于 /etc/haproxy/haproxy.cfg)。

bash 复制代码
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   https://www.haproxy.org/download/1.8/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    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

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    tcp
    log                     global
    option                  tcplog
    option                  dontlognull
    option                  redispatch
    retries                 3
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    maxconn                 3000

#---------------------------------------------------------------------
# MySQL frontend and backend configuration
#---------------------------------------------------------------------
frontend mysql_frontend
    bind *:3308
    default_backend mysql_backend

backend mysql_backend
    balance roundrobin
    server mysql1 172.19.0.2:3306 check
    server mysql2 172.19.0.3:3306 check

三、启动/重启/停止haproxy

1、启动haproxy

bash 复制代码
sudo systemctl start haproxy

2、重启haproxy

bash 复制代码
sudo systemctl restart haproxy

3、停止haproxy

bash 复制代码
sudo systemctl restart haproxy
相关推荐
鱼鳞_1 小时前
热门八股-MySQL
数据库·mysql
这个DBA有点耶1 小时前
数据库“家谱”系列之一:关系型数据库的4大核心组件详解
数据库·mysql·架构
Frank_refuel2 小时前
MYSQL【进阶】 -> 索引(了解)
数据库·mysql
l1t3 小时前
DeepSeek总结的DuckDB 如何更快地运行递归 CTE
java·开发语言·数据库·mysql·duckdb
csdn_aspnet5 小时前
mysql 函数、存储过程写法及示例
数据库·mysql·存储过程·函数·function·procedure
杨云龙UP6 小时前
Linux 下 MySQL 常用登录方式及 Socket 排查指南
linux·运维·数据库·mysql·登录·xtrabackup·主从复制
wear工程师8 小时前
MySQL 死锁怎么排查:把 innodb status 里的 HOLDS 和 WAITING 对上
sql·mysql
树下水月10 小时前
python3 使用canal监听后,kafka数据同步从mysql到clickhouse数据库 完整复盘
数据库·mysql·kafka
味悲10 小时前
HAProxy 负载均衡实战:从环境搭建到七层/四层/HTTPS 全解析
运维·https·负载均衡
东风破_10 小时前
博客数据库进阶设计:点赞、收藏、评论、标签与文件表怎么建?
后端·mysql