keepalived+nginx/mysql双主

目录

keepalived+nginx

编译安装nginx

编译安装keepalived

配置keepalived+nginx主从模式

keepalived配置文件介绍

主从配置 

keepalived启动与测试

配置keepalived+nginx双主模式

keepalived+mysql双主

yum安装mysql5.7

配置mysql双主

配置keepalived+mysql双主


keepalived+nginx

编译安装nginx

下载源码 ——> 官网nginx: download

#存放用户编译软件所用的源码目录
cd /usr/local/src  
wget https://nginx.org/download/nginx-1.22.0.tar.gz

安装编译所需依赖

yum install gcc gcc-c++ make automake autoconf libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel -y

编译安装nginx

tar -zxf nginx-1.22.0.tar.gz 
cd nginx-1.22.0
./configure --prefix=/usr/local/nginx
make && make install
#检查是否安装成功
/usr/local/nginx/sbin/nginx -t

启动

#启动
/usr/local/nginx/sbin/nginx 
#快速停止
/usr/local/nginx/sbin/nginx -s stop
#优雅的关闭,在退出前完成已经接受的连接请求
/usr/local/nginx/sbin/nginx -s quit 
#重读配置文件
/usr/local/nginx/sbin/nginx -s reload
#启动后尝试访问,网页访问需关闭防火墙或打开对应端口
本机访问 curl localhost

#开机自启(不添加为系统服务时,用此方法设置开机自启)
ll /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
vim /etc/rc.local
/usr/local/nginx/sbin/nginx
systemctl status rc-local
systemctl start rc-local

 添加为系统服务

vim /usr/lib/systemd/system/nginx.service

[Unit]
Description=nginx - web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecQuit=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

重新加载系统服务

systemctl daemon-reload

现在可以使用systemctl启动了

#开启Nginx服务
systemctl start nginx
#查看Nginx服务状态
systemctl status nginx
#设置开机启动
systemctl enable nginx

编译安装keepalived

软件下载 官网下载——>Keepalived for Linux

编译安装需要先安装依赖

yum install -y gcc  openssl-devel wget

从官网下载下载需要的版本,并解压

cd /usr/local/src
wget https://keepalived.org/software/keepalived-2.2.7.tar.gz --no-check-certificate
tar  zxf  keepalived-2.2.7.tar.gz

编译安装

cd /usr/local/src/keepalived-2.2.7
./configure --prefix=/usr/local/keepalived
make && make install

将keepalived添加到系统服务中(注意路径)

#复制/sbin/keepalived到/usr/sbin下
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/

#keepalived默认会读取/etc/keepalived/keepalived.conf配置文件
mkdir /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf.sample /etc/keepalived/keepalived.conf

#复制sysconfig文件到/etc/sysconfig下
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/

#复制keepalived 服务启动脚本到默认的地址/etc/init.d下
cp /usr/local/src/keepalived-2.2.7/keepalived/etc/init.d/keepalived /etc/init.d/
chmod 755 /etc/init.d/keepalived

启动测试

[root@masker ~]# service keepalived start
Starting keepalived (via systemctl):                       [  OK  ]
#提示正确或者OK,则表示安装成功
#设置开机自启
chkconfig keepalived on
chkconfig --list

配置keepalived+nginx主从模式

keepalived配置文件介绍

基础三个模块,global_defs全局模块,vrrp_instance配置vip模块,vrrp_script 脚本模块,用来检测nginx服务。

注:vrrp_script定义脚本后,在vrrp_instance模块必须加上track_script 参数。

global_defs模块参数

  • notification_email : keepalived在发生诸如切换操作时需要发送email通知地址,后面的 smtp_server 相比也都知道是邮件服务器地址。也可以通过其它方式报警,毕竟邮件不是实时通知的。

  • router_id : 机器标识,通常可设为hostname。故障发生时,邮件通知会用到。

vrrp_instance模块参数

  • state : 指定instance(Initial)的初始状态, MASTER 或者BACKUP,不是唯一性的,跟后面的优先级priority参数有关。

  • interface : 实例绑定的网卡,因为在配置虚拟IP的时候必须是在已有的网卡上添加的,(注意自己系统,我的默认是ens33,有的是eth0)

  • mcast_src_ip : 发送多播数据包时的源IP地址,这里注意了,这里实际上就是在那个地址上发送VRRP通告,这个非常重要,一定要选择稳定的网卡端口来发送,这里相当于heartbeat的心跳端口,如果没有设置那么就用默认的绑定的网卡的IP,也就是interface指定的IP地址

  • virtual_router_id : 这里设置VRID,这里非常重要,相同的VRID为一个组,他将决定多播的MAC地址

  • priority: 设置本节点的优先级,优先级高的为master(1-255)

  • advert_int : 检查间隔,默认为1秒。这就是VRRP的定时器,MASTER每隔这样一个时间间隔,就会发送一个advertisement报文以通知组内其他路由器自己工作正常

  • authentication : 定义认证方式和密码,主从必须一样

  • virtual_ipaddress : 这里设置的就是VIP,也就是虚拟IP地址,他随着state的变化而增加删除,当state为master的时候就添加,当state为backup的时候删除,这里主要是有优先级来决定的,和state设置的值没有多大关系,这里可以设置多个IP地址

  • track_script: 引用VRRP脚本,即在 vrrp_script 部分指定的名字。定期运行它们来改变优先级,并最终引发主备切换。

vrrp_script模块参数

告诉 keepalived 在什么情况下切换,所以尤为重要。可以有多个 vrrp_script

  • script : 自己写的检测脚本。也可以是一行命令如killall -0 nginx

  • interval 2: 每2s检测一次

  • weight -5 : 检测失败(脚本返回非0)则优先级 -5

  • fall 2: 检测连续 2 次失败才算确定是真失败。会用weight减少优先级(1-255之间)

  • rise 1 : 检测 1 次成功就算成功。但不修改优先级

主从配置 

修改配置文件前备份
cp /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
vim /etc/keepalived/keepalived.conf

修改主服务器keepalived配置文件

global_defs {               
   router_id Nginx_01
}
vrrp_script check_nginx {
        script "/etc/keepalived/check_nginx.sh"
        interval 2   
        weight -20     
}
vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    nopreempt 
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
     10.0.0.10
    }
    track_script {
    	check_nginx
    }
}

说明

interval 2   #执行时间间隔
weight -20     #动态调整vrrp_instance的优先级,成立,权重-5
!weight 为正数
 !如果脚本执行结果为 0,,Master:weight+priority>Backup:weight+priority(不切换)
 !如果脚本执行结果不为 0,Master:priorityBackup:priority(不切换)
 !如果脚本执行结果不为 0,Master:priority+weight

修改备份服务器keepalived配置文件

配置一样,就三点不同,一点必须相同,1. router_id 不同, 2. state BACKUP不同 ,3. priority不同。 4.virtual_router_id 必相同。

global_defs {               
   router_id Nginx_02            
}
vrrp_script check_nginx {
        script "/etc/keepalived/check_nginx.sh"
        interval 2   
        weight -20     
}
vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
      10.0.0.10
    }
    track_script {
    	check_nginx
    }
}

nginx脚本与配置

编写检测nginx存活状态脚本

脚本要求:如果 nginx 停止运行,尝试启动,如果无法启动则杀死本机的 keepalived 进程, keepalied将虚拟 ip 绑定到 BACKUP 机器上。

vim /etc/keepalived/check_nginx.sh
#!/bin/bash
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];then
  /usr/local/nginx/sbin/nginx
  sleep 2
  if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
     killall keepalived
  fi
fi

#保存后,给脚本赋执行权限:
chmod +x /etc/keepalived/check_nginx.sh

修改 Nginx 欢迎首页内容(用于后面测试, 用于区分两个节点的 Nginx):

# vim /usr/local/nginx/html/index.html
192.168.50.133 中的标题加 1

Welcome to nginx! 1

192.168.50.134 中的标题加 2

Welcome to nginx! 2

keepalived启动与测试

启动nginx服务,在启动keepalived服务:

syetemctl start keepalived
yetemctl status keepalived
#保险起见可以看一下是否存在相应进程
ps -ef |grep keepalived

分别在nginx主备两台用ip addr查看IP地址:主nginx1的网卡此时已经自动获取VIP,备nginx2则没有处于空闲状态

keepalived+nginx/mysql双主_第1张图片

在浏览器访问VIP:10.0.0.10,也正常

keepalived+nginx/mysql双主_第2张图片

shutdown主机,查看从机ip ,可以看到10.0.0.10,说明vip漂移成功

测试再次开启主机,查看主机ip,发现vip没有漂移回主机1上,这是因为在主机1keepalived配置文件中设置了nopreempt即不抢占,此时若关闭从机,vip才会重新漂移回主机上

配置keepalived+nginx双主模式

只需要在每台keepalived配置文件,加上一个vrrp_instance命名vrrp_instance VI_2即可,更改几个参数,设置另一个VIP:10.0.0.100

#nignx1
vrrp_instance VI_2 {
    state BACKUP
    interface ens33
    virtual_router_id 52
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
     192.168.200.210
    }
    track_script {
    	check_nginx
    }    
}
#nginx2
vrrp_instance VI_2 {
    state MASTER
    interface ens33
    virtual_router_id 52
    priority 150
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
     192.168.200.210
    }
    track_script {
    	check_nginx
    }    
}

启动测试,查看ip

在浏览器分别访问10.0.0.10和10.0.0.100都可以访问nginx

双主模式配置完成!!

keepalived+mysql双主

yum安装mysql5.7

首先卸载系统的低版本mysql,或自带的数据库

rpm -qa |grep -i mysql
rpm -qa |grep mariadb
yum -y remove mariadb-libs-5.5.64-1.el7.x86_64

 先去官网下载 Yum 资源包

wget https://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm

安装

#安装mysql源
rpm -ivh mysql57-community-release-el7-9.noarch.rpm
#也可yum安装mysql源,最后可删除源
#yum -y install mysql57-community-release-el7-9.noarch.rpm
#yum -y remove mysql57-community-release.noarch
#更新密钥
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
#安装mysql
yum install -y mysql-server

启动

systemctl start mysqld

进入mysql修改密码

#找到密码
grep "password" /var/log/mysqld.log
#进入mysql
mysql -u root -p
#修改密码字符集(密码长度和简易度)
mysql> set global validate_password_policy=0;
mysql> set global validate_password_length=1;
#修改新密码为root
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
mysql> quit
创建用户,开启远程访问
create user 'yuan'@'%' identified by '123456';
grant all on *.* to 'root'@'%' identified by 'root' with grant option;
grant all on *.* to 'yuan'@'%' identified by '123456' with grant option;
flush privileges;
设置开机启动
systemctl enable mysqld
systemctl daemon-reload

配置mysql双主

两台服务器安装好mysql

修改配置文件/etc/my.cnf,修改完成后重启一下mysql,systemctl restart mysqld

主机1

[mysqld]

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

symbolic-links=0
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

port=3306
server_id=1
log-bin=mysql-bin
binlog_format=mixed
relay-log=relay-bin
relay-log-index=slave-relay-bin.index
auto-increment-increment=2
auto-increment-offset=1

主机2

[mysqld]

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

symbolic-links=0
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

port=3306
server_id=2
log-bin=mysql-bin
binlog_format=mixed
relay-log=relay-bin
relay-log-index=slave-relay-bin.index
auto-increment-increment=2
auto-increment-offset=2

注意:mysql1和mysql只有server-id不同和auto-increment-offset不同,其他必须相同。

部分配置项解释如下:

  • binlog_format= mixed:指定mysql的binlog日志的格式,mixed是混合模式。

  • relay-log:开启中继日志功能

  • relay-log-index:中继日志清单

  • auto-increment-increment= 2:表示自增长字段每次递增的量,其默认值是1。它的值应设为整个结构中服务器的总数,本案例用到两台服务器,所以值设为2。

  • auto-increment-offset= 2:用来设定数据库中自动增长的起点(即初始值),因为这两能服务器都设定了一次自动增长值2,所以它们的起点必须得不同,这样才能避免两台服务器数据同步时出现主键冲突。

:另外还可以在my.cnf配置文件中,添加“binlog_do_db=数据库名”配置项(可以添加多个)来指定要同步的数据库。如果配置了这个配置项,如果没添加在该配置项后面的数据库,则binlog不记录它的事件。

#重启mysql
systemctl restart mysqld
#开启防火墙端口(两台都开)
firewall-cmd --permanent --add-port=3306/tcp
firewall-cmd --reload

将mysql1设为mysql2的主服务器

主机1

mysql -uroot -p
#在mysql1主机上创建授权账户,允许在mysql2(10.0.0.12)主机上连接
mysql> grant replication slave on *.* to 'fzx'@'10.0.0.12' identified by '123456';
#查看mysql1的当前binlog状态信息:
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 |      154 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

主机2

mysql -uroot -p
#在mysql2上将mysql1设为自已的主服务器并开启slave功能:
mysql> change master to master_host='10.0.0.11',master_user='fzx',master_password='123456',master_log_file='mysql-bin.000001',master_log_pos=154;
#先启动链路:
mysql> start slave;
#看一看mysql2的状态:
mysql> show slave status\G
*************************** 1. row ***************************
               
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
#这两项Yes即可
#IO线程和SQL进程都是Yes,表示主从复制成功

反过来,再将mysql2设为mysql1的主服务器

主机2

#在mysql2主机上创建授权账户,允许在mysql1(10.0.0.11)主机上连接
mysql> grant replication slave on *.* to 'fzx'@'10.0.0.11' identified by '123456';
#查看mysql2的当前binlog状态信息:
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 |      449 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

主机1

#在mysql1上将mysql2设为自已的主服务器并开启slave功能:
mysql> change master to master_host='10.0.0.12',master_user='fzx',master_password='123456',master_log_file='mysql-bin.000001',master_log_pos=449;
#先启动链路:
mysql> start slave;
#查看mysql1的状态:
mysql> show slave status\G
*************************** 1. row ***************************

             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
测试主主同步
在任意机器mysql中创建数据库,创建表,写入内容,在另一机上查看是否同步,若同步,则配置成功。

配置keepalived+mysql双主

在配置好双主的基础上配置,keepalived的安装参考前文

编辑keepalived配置文件

先编辑安全策略(两台都要做)否则主备节点机会都有VIP

#设置Selinux为宽容模式
[root@mysql_01 ~]# setenforce 0 
[root@mysql_01 ~]# sed -i 's/=enforcing/=disabled/g' /etc/sysconfig/selinux
#接着防火墙规则中增加开放VRRP:
[root@mysql_01 ~]# firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0  --protocol vrrp -j ACCEPT
success
[root@mysql_01 ~]# firewall-cmd --reload
success

修改主节点机器主机1的keepalived配置文件

[root@mysql_01 ~]# mv /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
[root@mysql_01 ~]# vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   router_id mysql_01
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    nopreempt
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.0.0.100
    }
}

virtual_server 10.0.0.100 3306 {
    delay_loop 2
    lb_algo rr
    lb_kind NAT
    persistence_timeout 60
    protocol TCP

    real_server 10.0.0.11 3306 {
        weight 3
        notify_down    /etc/keepalived/bin/mysql.sh
        TCP_CHECK {
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
            connect_port 3306
        }
    }
}
修改备机主机2的keepalived配置文件
! Configuration File for keepalived

global_defs {
   router_id mysql_02
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 50
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.0.0.100
    }
}

virtual_server 10.0.0.100 3306 {
    delay_loop 2
    lb_algo rr
    lb_kind NAT
    persistence_timeout 60
    protocol TCP

    real_server 10.0.0.12 3306 {
        weight 3
        notify_down    /etc/keepalived/bin/mysql.sh
        TCP_CHECK {
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
            connect_port 3306
        }
    }
}

编写检测脚本

[root@masker ~]# mkdir /etc/keepalived/bin
[root@masker ~]# vim /etc/keepalived/bin/mysql.sh
#!/bin/bash
pkill keepalived
/sbin/ifdown ens33 && /sbin/ifup ens33
[root@masker ~]# chmod +x /etc/keepalived/bin/mysql.sh 
[root@masker ~]# systemctl restart keepalived
在两台服务器上用 ip a 查看vip
主机1

keepalived+nginx/mysql双主_第3张图片

主机2 无vipkeepalived+nginx/mysql双主_第4张图片

测试

找一台安装有MySQL客户端的虚拟机,然后通过VIP地址登录mysql,看是否能登录,在登录之前两台MySQL服务器都要授权允许从远程登录

在客户端登录

[root@mysql_client ~]# mysql -uyuan -p123456 -h 10.0.0.100 -P3306

mysql> show variables like "server_id";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 1     |
+---------------+-------+
1 row in set (0.01 sec)
#说明在客户端访问VIP地址,由mysql_01主机提供响应的,因为mysql_01当前是主服务器
#将mysql_01的mysql服务停止,在客户端执行show  variables like‘server_id’;
mysql> show variables like "server_id";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 2     |
+---------------+-------+
1 row in set (0.00 sec)
#说明在客户端的查询请求是由mysql_02主机响应的,故障切换成功。

此时查看ip,发现vip漂移到mysql_02主机上

keepalived+nginx/mysql双主_第5张图片

重新启动主机1的mysql以及keepalived后,通过ip a查看,发现vip没有漂移回主机1上,这是因为在主机1keepalived配置文件中设置了nopreempt即不抢占,此时若关闭主机2,vip才会重新漂移回主机1上

至此配置完成

 

你可能感兴趣的:(linux下常用环境搭建,nginx,mysql,服务器)