Notes on building a MySQL dual-master cluster and adding Keepalived for VIP failover.

This is the old MySQL 5.7 + Keepalived approach. MySQL 5.7 is already EOL; for new environments, go straight to Group Replication on MySQL 8.0/8.4, or use tools like MHA or Orchestrator.

Environment Setup

OS: CentOS 7.x

Two virtual machines.

I disabled SELinux and the firewall in the lab to save time. Don’t do that in production; just allow 3306 and VRRP as needed.

systemctl disable firewalld
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config

Set the hostnames:

# node 1
hostnamectl set-hostname mysql-master1
# node 2
hostnamectl set-hostname mysql-master2

Download MySQL:

yum install wget -y
wget -c https://cdn.mysql.com/archives/mysql-5.7/mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz

Install dependencies:

yum install libaio numactl -y

Users and groups:

groupadd mysql
useradd -m -r -g mysql mysql

Set the system ulimit:

vi  /etc/security/limits.conf

Contents:

mysql     soft    nproc    65536
mysql     hard    nproc    65536
mysql     soft    nofile   65536
mysql     hard    nofile   65536

Open /etc/security/limits.d/90-nproc.conf and change the values to:

*          soft    nproc     65536
root       soft    nproc     unlimited
*          soft    nofile    65536
root       soft    nofile    unlimited

Add hosts entries:

host_ip=$(ifconfig | grep inet | grep cast | awk '{print $2}' | awk -F: '{print $NF}' | head -1)
echo "$host_ip `hostname`" >> /etc/hosts

Time synchronization:

yum install chrony -y
systemctl enable chronyd --now

MySQL Deployment

Install MySQL:

tar -xvzf mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz
mv mysql-5.7.35-linux-glibc2.12-x86_64 /usr/local/mysql57

Create symlinks:

ln -s  /usr/local/mysql57/bin/mysql /usr/bin/mysql
ln -s  /usr/local/mysql57/bin/mysqlbinlog /usr/bin/mysqlbinlog

Create the MySQL log and data directories:

mkdir -p /data/mysql_db/mysql_test
mkdir -p /data/mysql_log/mysql_test

Initialize:

/usr/local/mysql57/bin/mysqld --initialize-insecure --basedir=/usr/local/mysql57 --datadir=/data/mysql_db/mysql_test --user=mysql
/usr/local/mysql57/bin/mysql_ssl_rsa_setup --basedir=/usr/local/mysql57 --datadir=/data/mysql_db/mysql_test

Create the corresponding startup script:

cp /usr/local/mysql57/support-files/mysql.server /etc/init.d/mysqld-test

Modify /etc/init.d/mysqld-test as follows:

basedir=/usr/local/mysql57
datadir=/data/mysql_db/mysql_test
default_file=/data/mysql_db/mysql_test/my.cnf
lock_file_path="$lockdir/mysql-test"
$bindir/mysqld_safe  --defaults-file="$default_file" --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null 2>&1 &

Fix permissions:

chown mysql.mysql /etc/init.d/mysqld-test
chown mysql.mysql -R /data/mysql*

Start MySQL:


su - mysql
[mysql@mysql-master1 ~]$ /etc/init.d/mysqld-test start
Starting MySQL.. SUCCESS!

Test the connection:

mysql -S /data/mysql_db/mysql_test/mysql.sock

Edit the MySQL configuration:

vim /data/mysql_db/mysql_test/my.cnf

Both nodes keep the same directory layout; only server_id and auto_increment_offset differ. Below is master1:

mysql-master1

[client]
port = 3306
default-character-set=utf8mb4
socket = /data/mysql_db/mysql_test/mysql.sock

[mysqld]
datadir = /data/mysql_db/mysql_test
basedir = /usr/local/mysql57
tmpdir = /tmp
socket = /data/mysql_db/mysql_test/mysql.sock
pid-file = /data/mysql_db/mysql_test/mysql.pid
skip-external-locking = 1
skip-name-resolve = 1
port = 3306
server_id = 833306

default-storage-engine = InnoDB
character-set-server = utf8mb4
default_password_lifetime=0

auto_increment_offset = 1
auto_increment_increment = 2

#### log ####
log_timestamps=system
log_bin = /data/mysql_log/mysql_test/mysql-bin
log_bin_index = /data/mysql_log/mysql_test/mysql-bin.index
binlog_format = row
relay_log_recovery=ON
relay_log=/data/mysql_log/mysql_test/mysql-relay-bin
relay_log_index=/data/mysql_log/mysql_test/mysql-relay-bin.index
log_error = /data/mysql_log/mysql_test/mysql-error.log

#### replication ####
log_slave_updates = 1
replicate_wild_ignore_table = information_schema.%,performance_schema.%,sys.%

#### semi sync replication settings #####
plugin_dir=/usr/local/mysql57/lib/plugin
plugin_load = "rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so"
loose_rpl_semi_sync_master_enabled = 1
loose_rpl_semi_sync_slave_enabled = 1
loose_rpl_semi_sync_master_timeout = 5000

The master2 configuration is the same except for server_id, auto_increment_offset, and the hostname:

mysql-master2

[client]
port = 3306
default-character-set=utf8mb4
socket = /data/mysql_db/mysql_test/mysql.sock

[mysqld]
datadir = /data/mysql_db/mysql_test
basedir = /usr/local/mysql57
tmpdir = /tmp
socket = /data/mysql_db/mysql_test/mysql.sock
pid-file = /data/mysql_db/mysql_test/mysql.pid
skip-external-locking = 1
skip-name-resolve = 1
port = 3306
server_id = 723306

default-storage-engine = InnoDB
character-set-server = utf8mb4
default_password_lifetime=0

auto_increment_offset = 2
auto_increment_increment = 2

#### log ####
log_timestamps=system
log_bin = /data/mysql_log/mysql_test/mysql-bin
log_bin_index = /data/mysql_log/mysql_test/mysql-bin.index
binlog_format = row
relay_log_recovery=ON
relay_log=/data/mysql_log/mysql_test/mysql-relay-bin
relay_log_index=/data/mysql_log/mysql_test/mysql-relay-bin.index
log_error = /data/mysql_log/mysql_test/mysql-error.log

#### replication ####
log_slave_updates = 1
replicate_wild_ignore_table = information_schema.%,performance_schema.%,sys.%

#### semi sync replication settings #####
plugin_dir=/usr/local/mysql57/lib/plugin
plugin_load = "rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so"
loose_rpl_semi_sync_master_enabled = 1
loose_rpl_semi_sync_slave_enabled = 1
loose_rpl_semi_sync_master_timeout = 5000

Optional: if you also want a read-only replica (3307) on the same node, add this configuration.

[client]
port = 3307
default-character-set=utf8mb4
socket = /data/mysql_db/mysql_seg_3307/mysql.sock

[mysqld]
datadir = /data/mysql_db/mysql_seg_3307
basedir = /usr/local/mysql57
tmpdir = /tmp
socket = /data/mysql_db/mysql_seg_3307/mysql.sock
pid-file = /data/mysql_db/mysql_seg_3307/mysql.pid
skip-external-locking = 1
skip-name-resolve = 1
port = 3307
server_id = 833307
read_only=1

default-storage-engine = InnoDB
character-set-server = utf8mb4
default_password_lifetime=0

#### log ####
log_timestamps=system
log_bin = /data/mysql_log/mysql_seg_3307/mysql-bin
log_bin_index = /data/mysql_log/mysql_seg_3307/mysql-bin.index
binlog_format = row
relay_log_recovery=ON
relay_log=/data/mysql_log/mysql_seg_3307/mysql-relay-bin
relay_log_index=/data/mysql_log/mysql_seg_3307/mysql-relay-bin.index
log_error = /data/mysql_log/mysql_seg_3307/mysql-error.log

#### replication ####
replicate_wild_ignore_table = information_schema.%,performance_schema.%,sys.%

#### semi sync replication settings #####
plugin_dir=/usr/local/mysql57/lib/plugin
plugin_load = "rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so"
loose_rpl_semi_sync_master_enabled = 1
loose_rpl_semi_sync_slave_enabled = 1
loose_rpl_semi_sync_master_timeout = 5000

Deploying Keepalived

Install:

yum install -y keepalived

Edit /etc/keepalived/keepalived.conf and add the following configuration, adjusted to your environment:

global_defs {
   router_id MYSQL_MM  # identifier
   vrrp_skip_check_adv_addr
   vrrp_strict        # strictly enforce the VRRP protocol spec
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_script check_mysql {
    script "/bin/bash /etc/keepalived/keepalived_mysql_check.sh"  # check script
    interval 10  # check interval
}

vrrp_instance MYSQL_MM {
    state BACKUP            # set both to BACKUP so they don't preempt on startup
    interface eth0          # network interface, adjust to your setup
    virtual_router_id 243   # identifies the VRRP multicast group, range 0-255
    priority 100
    advert_int 1
    nopreempt               # disable preemption
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    # don't use 1111 for auth_pass; use a random string, the same on both nodes

    # on the master node you can comment out the line below to avoid running the script when keepalived starts
    notify_master "/bin/bash /etc/keepalived/keepalived_mysql_start.sh"  # runs when transitioning to MASTER

    virtual_ipaddress {
        10.0.0.237
    }

    # on the slave node you can comment out the check script below; the slave doesn't need to keep checking
    track_script {
        check_mysql
    }
}

The check script connects to MySQL as the monitor user, so create it on both nodes first:

create user 'monitor'@'localhost' identified by 'monitor';
grant process, replication client on *.* to 'monitor'@'localhost';

Change the password to your own and keep it consistent with MYSQL_PWD in the script.

Create and edit /etc/keepalived/keepalived_mysql_check.sh with the check script:

#!/bin/sh
# MySQL check script
MyPath=$(cd $(dirname $0); pwd)
cd $MyPath

ThisTime=`date '+%F %T'`
log_file='/var/log/keepalived_mysql.log'

# MySQL connection settings, adjust to your environment
export MYSQL_PWD='monitor'
MYSQL_USER='monitor'
MYSQL_SOCKET="/data/mysql_db/mysql_test/mysql.sock"
mysql_connect="mysql -u${MYSQL_USER} -S${MYSQL_SOCKET} "

# pretty output
function techo() {
    message=$1
    message_level=$2
    if [ -z "$message_level" ]; then
        message_level='info'
    fi
    echo "`date '+%F %T'` - [${message_level}] $message" >> $log_file
}

# check function, returns 0 on success
function check {
    ret=`$mysql_connect -N -e 'select 1 as value'`
    if [ $? -ne 0 ] || [ "$ret" != "1" ]; then
        return 1
    else
        return 0
    fi
}

function read_only {
    param=$1
    $mysql_connect -e "set global read_only = ${param}"
    techo "Setting read_only to ${param}"
}

# failover
function failover {
    techo "Starting failover"
    # 1. stop keepalived
    killall keepalived

    # 2. if it's still possible, set read_only
    read_only 1

    if [ $? -eq 0 ];then
        # 3. if it's still possible, kill all connections
        $mysql_connect -e "select concat('KILL ',id,';') from information_schema.processlist where user!='root' AND db is not null into outfile '/tmp/kill.txt.${ThisTime}';"
        if [ $? -eq 0 ];then
            $mysql_connect -e "source /tmp/kill.txt.${ThisTime};"
        fi
    fi

    # 4. other actions, e.g. automatic shutdown

    techo "Failover succeeded; the database is now closed to access"
}

# check 4 times when there's a problem
for ((i=1; i<=4; i ++))  
do  
    check
    if [ $? -eq 0 ];then
        techo "MySQL is ok"
        # exit the script normally
        exit 0
    else
        techo "Connection failed $i time(s)"
        sleep 1
    fi
done

techo 'Cannot connect to the current database'

# failover
failover

Open /etc/keepalived/keepalived_mysql_start.sh and write the script contents:

#!/bin/sh
# runs when keepalived becomes Master
MyPath=$(cd $(dirname $0); pwd)
cd $MyPath

ThisTime=`date '+%F %T'`
log_file='/var/log/keepalived_mysql.log'

# MySQL connection settings, adjust to your environment
export MYSQL_PWD='monitor'
MYSQL_USER='monitor'
MYSQL_SOCKET="/data/mysql_db/mysql_test/mysql.sock"
mysql_connect="mysql -u${MYSQL_USER} -S${MYSQL_SOCKET} "

# pretty output
function techo() {
    message=$1
    message_level=$2
    if [ -z "$message_level" ]; then
        message_level='info'
    fi
    echo "`date '+%F %T'` - [${message_level}] $message" >> $log_file
}

# check function, returns 0 on success
function check {
    ret=`$mysql_connect -N -e 'select 1 as value'`
    if [ $? -ne 0 ] || [ "$ret" != "1" ]; then
        return 1
    else
        return 0
    fi
}

# get slave status information
function slave_info() {
    tmp_file=/tmp/slave_info.tmp
    $mysql_connect -e 'show slave status\G' > /tmp/slave_info.tmp
    slave_sql=`grep 'Slave_SQL_Running:' $tmp_file | sed 's/\s*//g' | tr "A-Z" "a-z"  | awk -F":" '{print $2}'`
    seconds_behind_master=`grep 'Seconds_Behind_Master:' $tmp_file | sed 's/\s*//g' | tr "A-Z" "a-z"  | awk -F":" '{print $2}'`

    master_log_file=`grep 'Master_Log_File:' $tmp_file | head -1 | sed 's/\s*//g' | tr "A-Z" "a-z"  | awk -F":" '{print $2}'`
    master_log_pos=`grep 'Read_Master_Log_Pos:' $tmp_file | sed 's/\s*//g' | tr "A-Z" "a-z"  | awk -F":" '{print $2}'`

    relay_master_log_file=`grep 'Relay_Master_Log_File:' $tmp_file | sed 's/\s*//g' | tr "A-Z" "a-z"  | awk -F":" '{print $2}'`
    exec_master_log_pos=`grep 'Exec_Master_Log_Pos:' $tmp_file | sed 's/\s*//g' | tr "A-Z" "a-z"  | awk -F":" '{print $2}'`

}

# set whether the database is readable
function read_only {
    param=$1
    $mysql_connect -e "set global read_only = ${param}"
    techo "Setting read_only to ${param}"
}

# handle data synchronization
function sync_master_log() {
    # if data consistency comes first, wait for replication to finish. If service availability comes first, comment out the code below
    slave_info
    if [ $slave_sql == "yes" ];then
        techo "Current sync position on master: ${master_log_file} ${master_log_pos}"
        techo "Waiting to catch up to master ${master_log_file} ${master_log_pos}"
        $mysql_connect -e "select master_pos_wait('$master_log_file', $master_log_pos);" > /dev/null
        techo "Sync complete"
    fi
}

techo "Promoting the current database to primary"

check
if [ $? -ne 0 ];then
    techo "Cannot connect to the current database"
    exit 1
fi

# wait for synchronization
sync_master_log

# set writable
read_only 0

Log in to MySQL and create the replication user; replace <peer-ip> with the other node’s address:

grant replication slave on *.* to 'sync'@'<peer-ip>' identified by '<sync-password>';
show master status;

Stop the slave:

stop slave;

Configure replication. Set master_host to the other node’s IP; the two nodes are master and slave to each other, so configure both directions. Use the other node’s show master status values for master_log_file and master_log_pos:

change master to
master_host='<peer-ip>',
master_user='sync',
master_password='<sync-password>',
master_log_file='mysql-bin.000003',
master_log_pos=154,
master_port=3306;
start slave;

Check the slave status:

show slave status\G;

Both Slave_IO_Running and Slave_SQL_Running should be Yes.

References