搭建MySql

Posted by Qiuyu Zhang on 2019-12-10

Linux服务器搭建Mysql

  1. 创建mysql用户组
    1
    2
    sudo groupadd mysql
    sudo useradd -g mysql mysql
  2. 创建mysql初始化目录
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    ${instport}为新建的实例端口号,如3306
    sudo mkdir -p /home/mysql/multi/${instport}/lock
    sudo mkdir -p /home/mysql/multi/${instport}/etc
    sudo mkdir -p /home/mysql/multi/${instport}/log
    sudo mkdir -p /home/mysql/multi/${instport}/pid
    sudo mkdir -p /home/mysql/multi/${instport}/socket
    sudo mkdir -p /home/mysql/multi/${instport}/tmp
    注意binlog和data目录放到数据盘:
    sudo mkdir -p /data1/mysql/multi/${instport}/binlog
    sudo mkdir -p /data1/mysql/multi/${instport}/data
  3. 在/home/mysql/multi/${instport}/etc中放入my.cnf配置文件
    拿走不谢
  4. 解压mysql安装包并创建软链接
    1
    2
    tar -zxvf mysql-5.7.28-linux-glibc2.12-x86_64.tar.gz -C 解压到指定目录
    ln -s /解压路径/mysql-5.7.28-linux-glibc2.12-x86_64 /home/mysql/base
  5. 修改用户组:
    1
    2
    sudo chown -R mysql:mysql /home/mysql/
    sudo chown -R mysql:mysql /data1/mysql/
  6. 初始化mysql实例,以3306实例为例:
    1
    sudo /home/mysql/base/bin/mysqld --defaults-file=/home/mysql/multi/${instport}/etc/my.cnf --initialize
    注意1:
    1
    2
    3
    4
    如果初始化时,出现如下报错:
    /home/mysql/base/bin/mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: No such file or directory
    解决方法:
    sudo yum install -y libaio
    注意2:
    1
    2
    如果需要重新执行初始化命令,则需要先删掉数据目录下的所有内容,然后再执行初始化命令:
    sudo rm -rf /data1/mysql/multi/${instport}/data/*
  7. 初始化后找到/home/mysql/multi/${instport}/log/mysql-error.log输出的密码,用作root登录
    1
    2
    3
    4
    5
    找临时密码的方法:
    sudo cat /home/mysql/multi/${instport}/log/mysql-error.log |grep 'temporary password'
    找到如下内容:
    A temporary password is generated for root@localhost: aXnUAxMil45d2
    密码为:aXnUAxMil45d2
  8. 在/home/mysql下面增加mysql服务启动/停止脚本
    拿走不谢
  9. 启动mysql服务:
    1
    sudo -u mysql bash /home/mysql/mysql.sh  -P ${instport} start
  10. 临时登录mysql
    1
    sudo /home/mysql/base/bin/mysql -h localhost -S /home/mysql/multi/${instport}/socket/mysql.sock  -uroot -P${instport} -p'aXnUAxMil45d2'
  11. 登录后,首先修改mysql root默认密码及host:
    1
    2
    SET PASSWORD FOR 'root'@'localhost'='新密码'; 
    flush privileges;
  12. 执行 exit 退出,重新登录
    1
    sudo /home/mysql/base/bin/mysql -h localhost -uroot -P${instport} -pnewPassword
  13. 修改支持主机ip方式连接
    1
    2
    update mysql.user set host='%' where host='localhost'and `user`='root';
    flush privileges;
    执行exit退出,就可以使用本机Ip连接了,也可以使用Navicat远程连接

至此!已经搭建完成,祝您工作愉快!!!