使用 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
相关推荐
我真的是大笨蛋12 分钟前
MySQL临时表深度解析
java·数据库·sql·mysql·缓存·性能优化
想摆烂的不会研究的研究生12 分钟前
Go后端场景——海量数据去重
经验分享·golang·负载均衡
南屿欣风26 分钟前
MySQL Binlog 数据恢复实战
数据库·mysql
Wzx1980121 小时前
go聊天室接入mysql的项目docker部署流程
mysql·docker·golang
梦想的旅途21 小时前
企微全自动化运营的可视化与度量
数据库·mysql
定偶1 小时前
C语言操作MYSQL
c语言·mysql·adb
Yeats_Liao1 小时前
负载均衡设计:多节点集群下的请求分发与资源调度
运维·人工智能·深度学习·机器学习·华为·负载均衡
Nandeska1 小时前
11、MySQL主从复制的基本概念
数据库·mysql
风吹落叶花飘荡10 小时前
2026年mysql数据库迁移(全流程)
数据库·mysql
液态不合群11 小时前
【面试题】MySQL 的索引下推是什么?
数据库·mysql