使用 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
相关推荐
q***31839 分钟前
MySQL---存储过程详解
数据库·mysql
q***428212 分钟前
MySQL数据库误删恢复_mysql 数据 误删
数据库·mysql·adb
6***B481 小时前
Nginx搭建负载均衡
运维·nginx·负载均衡
Hello.Reader1 小时前
在 Flink Standalone 集群上运行 Flink CDC从下载到跑起一个 MySQL→Doris 同步任务
大数据·mysql·flink
2***d8851 小时前
使用 MySQL 从 JSON 字符串提取数据
mysql·oracle·json
小满、2 小时前
MySQL :锁机制、InnoDB 架构与 MVCC 解析
数据库·mysql·innodb·mvcc·锁机制
Sam_Deep_Thinking2 小时前
在 MySQL 里,不建议使用长事务的根因
mysql
5***r9352 小时前
开源数据同步中间件(Dbsyncer)简单玩一下 mysql to mysql 的增量,全量配置
mysql·中间件·开源
2301_789380497 小时前
vsc中使用DBHub-MCP连接云Mysql到vsc-copilot
数据库·mysql