keepalived可以监控服务状态,当主服务宕机后可以将服务自动漂移至从服务,利用keepalived+mysql可以实现mysql的高可用性,当mysql主服务器宕机后,从服务器接管主服务器的工作,保证对外服务,keepalived还可以实现虚拟ip对外服务,保证内部服务器安全,同时keepalived的主从机制也保证了服务的高可用性
2.keepalived安装
这里和前边博文中keepalived安装步骤基本一样,主要是配置文件不一样,博主为熟悉keepalived安装又啰嗦了一遍,下载keepalived源码安装包,解压
进入keepalived解压目录,执行
./configure --prefix=/usr/local/keepalived
拷贝keepalived启动文件到/etc/init.d下,这样keepalived服务才能为系统识别
cp /root/package/keepalived-1.4.5/keepalived/etc/init.d /etc/init.d
执行
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
cp /usr/local/keepalived/sbin/keepalived /usr/sbin
新建文件夹keepalived
mkdir /etc/keepalived
将keepalived的配置文件拷贝过来,keepalived启动时会从/etc/keepalived目录下查找keepalived.conf配置文件,如果没有找到则使用默认的配置。
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
以上操作在keepalived主机和备机上都执行
修改主机配置文件
修改备机配置文件
主机和备机配置文件只有router_id和vrrp_instance的state和priority不同
开启主机和备机的keepalived服务
service keepalived start
在测试机上ping 虚拟IP192.168.174.222,成功,而且我的内网内192.168.174.222的ip
使用虚拟IP192.168.174.222连接3306端口的mysql服务,连接之前需要在mysql主服务和mysql从服务器为测试机ip赋予权限
使用虚拟IP192.168.174.222连接3306端口的mysql服务,使用授权的用户和密码,成功
查看当前数据库
查看mysql从服务器数据库可知连接的应该是从数据库
停止mysql从服务器服务:service mysqld stop,再次在测试机连接虚拟IP192.168.174.222连接3306端口的mysql服务,成功
也可以查出数据库
keepalived+mysql主从同步成功
四、MySQL读写分离