mysql+keepalived
1.安裝
# yum install -y openssl-devel popt-devel
# tar zxf keepalived-1.2.8.tar.gz
# cd keepalived-1.2.8
# ./configure --prefix=/usr/local/keepalived
# make && make install
2.將keepalived命令、啓動腳本及配置文件複製到相應目錄下並啓動服務
# which keepalived
/usr/local/sbin/keepalived
# ln -s /usr/local/keepalived/sbin/keepalived /usr/bin/keepalived
# cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
# cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig
# /etc/init.d/keepalived start
3.創建配置文件及檢測腳本
# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
root@localhost
}
notification_email_from keepalived@localhost
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script check_mysql {
script "/root/check_mysql.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER #mysql2此處改爲BACKUP
interface eth1
virtual_router_id 51
priority 100 #mysql此處改爲90,或小於100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_mysql
}
virtual_ipaddress {
192.168.36.200/24 dev eth1
}
}
# check_mysql.sh
MYSQL=/usr/bin/mysql
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=redhat
$MYSQL -h $MYSQL_HOST -u $MYSQL_USER -p$MYSQL_PASSWORD -e "show status;" >/dev/null 2>&1
#$mysqlclient --host=$host --port=$port --user=$user --password=$password -e "show databases;" > /dev/null 2>&1
if [ $? == 0 ]
then
echo " $host mysql login successfully"
exit 0
else
#echo " $host mysql login faild" #若mysql關閉,則keepalived關閉
/etc/init.d/keepalived stop
exit 2
fi
4.數據庫授權遠程登錄
# mysql -p
mysql> grant all privileges on *.* to 'root'@'%' identified by 'redhat';
mysql> flush privileges;
# mysql -uroot -predhat -h192.168.36.200 #vip登錄
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| cheungssh |
| discuz |
| mysql |
+--------------------+
4 rows in set (0.03 sec)
mysql> quit
Bye
5.檢測
此時vip在mysql1的eth1上,且兩端的mysql、keepalived均開啓
# ip a
eth1:
inet 192.168.36.160/24 brd 192.168.36.255 scope global eth1
inet 192.168.36.200/24 scope global secondary eth1
# /etc/init.d/mysqld status
mysqld (pid 7219) is running...
# /etc/init.d/keepalived status
keepalived (pid 7248) is running...
MYSQL1端:關閉mysql1的mysql服務,keepalived會自動關閉且vip飄在mysql2上
# /etc/init.d/mysqld stop
Stopping mysqld: [ OK ]
# /etc/init.d/mysqld status
mysqld is stopped
# /etc/init.d/keepalived status
keepalived is stopped
MYSQL2端:查看vip
# ip a
eth1:
inet 192.168.36.161/24 brd 192.168.36.255 scope global eth1
inet 192.168.36.200/24 scope global secondary eth1
MYSQL1端:開啓mysql、keepalived服務,vip飄回來
# /etc/init.d/mysqld start
Starting mysqld: [ OK ]
# /etc/init.d/keepalived start
Starting keepalived: [ OK ]
# ip a
2: eth1:
inet 192.168.36.160/24 brd 192.168.36.255 scope global eth1
inet 192.168.36.200/24 scope global secondary eth1