Keepalived是一個Linux下的高可用性方案,可以用來實現網絡負載均衡和故障切換。Keepalived通過VRRP協議(虛擬路由器冗余協議)來實現多個服務器之間的負載均衡和故障切換。本文將介紹如何使用Keepalived、MySQL和HAProxy實現高可用性的MySQL數據庫。
首先,我們需要在每臺MySQL服務器上安裝并啟用Keepalived。這里使用CentOS 7.0為例:
yum install keepalived -y # 安裝 keepalived systemctl enable keepalived && systemctl start keepalived # 啟動 keepalived
接著,我們需要創建MySQL主從復制。通過在主服務器上執行以下命令,創建同步用戶并授權:
CREATE USER 'repl'@'%' IDENTIFIED BY 'password'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%'; FLUSH PRIVILEGES; FLUSH TABLES WITH READ LOCK; SHOW MASTER STATUS; # 記錄下File, Position信息,備用
然后,在從服務器上執行以下命令,連接到主服務器并啟動復制:
CHANGE MASTER TO MASTER_HOST='master_host_name', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_LOG_FILE='recorded_file_name', MASTER_LOG_POS=recorded_position; START SLAVE;
接下來,我們需要在每臺MySQL服務器上安裝HAProxy。這里也使用CentOS 7.0為例:
yum install haproxy -y # 安裝 haproxy systemctl enable haproxy && systemctl start haproxy # 啟動 haproxy
最后,在HAProxy服務器上創建MySQL負載均衡,并配置Keepalived:
global log 127.0.0.1 local0 log 127.0.0.1 local1 notice maxconn 4096 defaults log global mode http option tcplog option dontlognull retries 3 timeout connect 3s timeout client 30s timeout server 30s listen mysql-replication bind *:3306 mode tcp balance roundrobin option mysql-check user haproxy_check server slave1 slave1_ip:3306 check port 3306 inter 3s server slave2 slave2_ip:3306 check port 3306 inter 3s vrrp_script chk_haproxy { script "/usr/bin/killall -0 haproxy" interval 2 } vrrp_instance VI_1 { interface eth0 state MASTER virtual_router_id 51 priority 101 virtual_ipaddress { haproxy_vip } authentication { auth_type PASS auth_pass keepalived_password } track_script { chk_haproxy } }
其中,mysql-replication為HAProxy監聽的端口,haproxy_check為連接mysql的用戶,slave1、slave2為MySQL從服務器的IP地址,haproxy_vip為HAProxy的虛擬IP地址,keepalived_password為Keepalived的密碼。
通過上述步驟,我們就實現了一個基于Keepalived、MySQL和HAProxy的高可用性方案,保證了MySQL數據庫的可靠運行。