数据库主从服务

数据库主从

    • 环境初始化
    • 配置数据库主从
      • 配置mysql01主节点
      • 配置mysql02从节点
    • 验证

环境初始化

参考我的初始化脚本,此服务器环境centos7.9

节点 IP
mysql01 192.168.200.80
mysql02 192.168.200.81

双节点执行此脚本

[root@localhost ~]# cat init.sh
#!/bin/bash

# 定义节点信息
NODES=("192.168.200.80 mysql01" "192.168.200.81 mysql02")

# 定义当前节点的密码(默认集群统一密码)
HOST_PASS="000000"

# 时间同步的目标节点
TIME_SERVER=mysql01

# 时间同步的地址段
TIME_SERVER_IP=192.160.200.0/24

# 欢迎界面
cat > /etc/motd <################################
 #    Welcome  to  mycluster    #
 ################################
EOF

#禁用selinux
sed -i 's/SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
setenforce 0

#firewalld
systemctl stop firewalld
systemctl disable firewalld  >> /dev/null 2>&1

#关闭IPtables,清空规则
yum install  iptables-services  -y
if [ 0  -ne  $? ]; then
        echo -e "\033[31mThe installation source configuration errors\033[0m"
        exit 1
fi
systemctl restart iptables
iptables -F
iptables -X
iptables -Z
/usr/sbin/iptables-save
systemctl stop iptables
systemctl disable iptables

#禁用NetworkManager
systemctl stop NetworkManager >> /dev/null 2>&1
systemctl disable NetworkManager >> /dev/null 2>&1
yum remove -y NetworkManager firewalld
systemctl restart network

# 优化ssh连接
sed -i -e 's/#UseDNS yes/UseDNS no/g' -e 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/g' /etc/ssh/sshd_config
systemctl reload sshd

# 修改主机名
for node in "${NODES[@]}"; do
  ip=$(echo "$node" | awk '{print $1}')
  hostname=$(echo "$node" | awk '{print $2}')

  # 获取当前节点的主机名和 IP
  current_ip=$(hostname -I | awk '{print $1}')
  current_hostname=$(hostname)

  # 检查当前节点与要修改的节点信息是否匹配
  if [[ "$current_ip" == "$ip" && "$current_hostname" != "$hostname" ]]; then
    echo "Updating hostname to $hostname on $current_ip..."
    hostnamectl set-hostname "$hostname"

    if [ $? -eq 0 ]; then
      echo "Hostname updated successfully."
    else
      echo "Failed to update hostname."
    fi

    break
  fi
done

# 遍历节点信息并添加到 hosts 文件
for node in "${NODES[@]}"; do
  ip=$(echo "$node" | awk '{print $1}')
  hostname=$(echo "$node" | awk '{print $2}')

  # 检查 hosts 文件中是否已存在相应的解析
  if grep -q "$ip $hostname" /etc/hosts; then
    echo "Host entry for $hostname already exists in /etc/hosts."
  else
    # 添加节点的解析条目到 hosts 文件
    sudo sh -c "echo '$ip $hostname' >> /etc/hosts"
    echo "Added host entry for $hostname in /etc/hosts."
  fi
done

if [[ ! -s ~/.ssh/id_rsa.pub ]]; then
    ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q -b 2048
fi

# 检查并安装 expect 工具
if ! which expect &> /dev/null; then
    echo "expect 工具未安装,正在安装 expect..."
    sudo yum install -y expect
fi

# 遍历所有节点
for node in "${NODES[@]}"; do
    ip=$(echo "$node" | awk '{print $1}')
    hostname=$(echo "$node" | awk '{print $2}')

    expect -c "
        set timeout -1
        spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $hostname
        expect {
            \"*password:*\" { send -- \"$HOST_PASS\r\"; exp_continue }
            \"*(yes/no)*\" { send -- \"yes\r\"; exp_continue }
            eof { exit 1 }
        }
    "
done

# 时间同步
if [[ $name == $TIME_SERVER ]]; then
    # 配置当前节点为时间同步源`[root@localhost ~]# bash
[root@mysql01 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.80 mysql01
192.168.200.81 mysql02
[root@mysql01 ~]#`
    sed -i '3,6s/^/#/g' /etc/chrony.conf
    sed -i "7s/^/server $TIME_SERVER iburst/g" /etc/chrony.conf
    echo "allow $TIME_SERVER_IP" >> /etc/chrony.conf
    echo "local stratum 10" >> /etc/chrony.conf
else
    # 配置当前节点同步到目标节点
    sed -i '3,6s/^/#/g' /etc/chrony.conf
    sed -i "7s/^/server $TIME_SERVER iburst/g" /etc/chrony.conf
fi

# 重启并启用 chrony 服务
systemctl restart chronyd
systemctl enable chronyd

echo "###############################################################"
echo "#################      集群初始化成功     #####################"
echo "###############################################################"

[root@localhost ~]#

脚本初始化完成

[root@localhost ~]# bash
[root@mysql01 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.80 mysql01
192.168.200.81 mysql02
[root@mysql01 ~]#
[root@localhost ~]# bash
[root@mysql02 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.80 mysql01
192.168.200.81 mysql02
[root@mysql02 ~]#

配置数据库主从

安装软件包

[root@mysql01 ~]# yum install -y mariadb mariadb-server
[root@mysql02 ~]# yum install -y mariadb mariadb-server

分别设置开机自启动

[root@mysql01 ~]# systemctl enable --now mariadb
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@mysql01 ~]#
[root@mysql02 ~]# systemctl enable --now mariadb
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@mysql02 ~]#

初始化数据库密码000000

[root@mysql01 ~]# mysql_secure_installation
# 回车
# y
# 000000
# 000000
# y
# n
# y
# y
[root@mysql02 ~]# mysql_secure_installation
# 回车
# y
# 000000
# 000000
# y
# n
# y
# y

配置mysql01主节点

在配置文件/etc/my.cnf.d/server.cnf中的[mysqld]增添如下内容

[root@mysql01 ~]# vi /etc/my.cnf.d/server.cnf
[mysqld]
log_bin = mysql-bin                       #记录操作日志
binlog_ignore_db = mysql                  #不同步mysql系统数据库
server_id = 80                            #数据库集群中的每个节点id都要不同

重启数据库,并进入配置

[root@mysql01 ~]# systemctl restart mariadb
[root@mysql01 ~]# mysql -uroot -p000000
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> grant all privileges  on *.* to root@'%' identified by "000000";
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> grant replication slave on *.* to 'user'@'mysql02' identified by '000000';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]>

配置mysql02从节点

在配置文件/etc/my.cnf.d/server.cnf中的[mysqld]增添如下内容

[root@mysql02 ~]# vi /etc/my.cnf.d/server.cnf
[mysqld]
log_bin = mysql-bin                       #记录操作日志
binlog_ignore_db = mysql                  #不同步mysql系统数据库
server_id = 80                            #数据库集群中的每个节点id都要不同

重启数据库服务,并配置,注意连接信息的master节点名需要对应,使用show slave status\G命令,并查看从节点服务状态,如果Slave_IO_Running和Slave_SQL_Running的状态都为YES,则从节点服务开启成功

[root@mysql02 ~]# systemctl restart mariadb
[root@mysql02 ~]# mysql -uroot -p000000
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> change master to master_host='mysql01',master_user='user',master_password='000000';
Query OK, 0 rows affected (0.02 sec)

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: mysql01
                  Master_User: user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 531
               Relay_Log_File: mariadb-relay-bin.000002
                Relay_Log_Pos: 815
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 531
              Relay_Log_Space: 1111
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 80
1 row in set (0.00 sec)

MariaDB [(none)]>

验证

MariaDB [(none)]> create database huhy;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> exit
Bye
[root@mysql01 ~]#
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| huhy               |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)

MariaDB [(none)]> exit
Bye
[root@mysql02 ~]#

注;如果需要配置一主多从的数据库集群,只需要主节点创建从节点连接信息,从节点再连接主节点即可

你可能感兴趣的:(数据库,Linux,数据库)