Setting up a load-balanced MySQL environment with HAProxy and replication improves performance and reliability. HAProxy acts as a load balancer, routing requests between the master and slave databases. This setup is useful for distributing read operations across multiple slave servers while the master server handles write operations.
In this configuration, MySQL replication keeps the data in sync between the master and the slaves. The master sends changes to the slaves, which replicate the data. This setup is typically used for scaling read-heavy applications.
The following steps guide you through setting up a MySQL master-slave replication with HAProxy. This includes configuring the master and slave databases, enabling replication, and setting up HAProxy for load balancing.
Steps to set up load-balanced MySQL with HAProxy and replication:
- Install MySQL on the master and slave servers.
$ sudo apt-get install mysql-server
- Enable binary logging and set the server-id on the master server.
[mysqld] server-id=1 log_bin=mysql-bin
- Restart the MySQL service.
$ sudo systemctl restart mysql
- Create a user with replication privileges on the master server.
CREATE USER 'repl_user'@'%' IDENTIFIED BY 'password'; GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'%'; FLUSH PRIVILEGES;
- Set a unique server-id on each slave. Connect the slave to the master using the binary log position.
[mysqld] server-id=2 relay-log=relay-bin
- Restart MySQL on the slave.
$ sudo systemctl restart mysql
- Configure replication on the slave.
CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='repl_user', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=0; START SLAVE;
- Check the replication status on each slave.
SHOW SLAVE STATUS\G;
Ensure that Slave_IO_Running and Slave_SQL_Running are both set to Yes.
- Install HAProxy to act as a load balancer for the MySQL servers.
$ sudo apt-get install haproxy
- Modify the HAProxy configuration to distribute queries across the master and slave servers.
$ sudo nano /etc/haproxy/haproxy.cfg
- Add the following configuration.
frontend mysql_front bind *:3306 default_backend mysql_back backend mysql_back balance roundrobin server mysql1 192.168.0.101:3306 check server mysql2 192.168.0.102:3306 check
- Start HAProxy and check if it is balancing traffic correctly between the master and slave databases.
$ sudo systemctl start haproxy
- Test the load balancer by connecting to the MySQL cluster.
$ mysql -h haproxy_ip -u root -p

Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
Comment anonymously. Login not required.