1、查看当前数据库存储路径
qiang@09230:~$ mysql -uroot -p
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.28-0ubuntu0.20.04.3 (Ubuntu)
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
mysql> show variables like 'datadir';
+---------------+-----------------+
| Variable_name | Value |
+---------------+-----------------+
| datadir | /var/lib/mysql/ |
+---------------+-----------------+
1 row in set (0.01 sec)
mysql>
2、停止MySQL服务
qiang@09230:~$ sudo service mysql stop
qiang@09230:~$
3、创建新的存储文件,并将MySQL的数据复制到新的目录中
#创建新存储目录
qiang@09230:~$ sudo mkdir -p /data/mysql
#将MySQL的数据复制到新的目录中
qiang@09230:~$ sudo cp -ar /var/lib/mysql /data/mysql
#修改新存储目录权限,使该目录的所有者和所属组只能是mysql用户
qiang@09230:~$ sudo chown -R mysql:mysql /data/mysql
4、修改MySQL的配置文件:
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
将datadir = /var/lib/mysql 改成 datadir = /data/mysql/mysql
如果出现如下权限限制的话,先输入:set noreadonly 再输入:wq 保存后退出
5、修改安全保护文件
sudo vim /etc/apparmor.d/usr.sbin.mysqld
将
/var/lib/mysql/ r,
/var/lib/mysql/** rwk,
改成
/data/mysql/mysql/ r,
/data/mysql/mysql/** rwk,
# Allow data dir access
# /var/lib/mysql/ r,
# /var/lib/mysql/** rwk,
/data/mysql/mysql/ r,
/data/mysql/mysql/** rwk,
6、修改mysql访问控制文件
sudo vim /etc/apparmor.d/abstractions/mysql
将
/var/lib/mysql{,d}/mysql{,d}.sock rw,
改成
/data/mysql/mysql{,d}/mysql{,d}.sock rw,
# /var/lib/mysql{,d}/mysql{,d}.sock rw,
/data/mysql/mysql{,d}/mysql{,d}.sock rw,
/{var/,}run/mysql{,d}/mysql{,d}.sock rw,
/usr/share/{mysql,mysql-community-server,mariadb}/charsets/ r,
/usr/share/{mysql,mysql-community-server,mariadb}/charsets/*.xml r,
7、重启服务
qiang@09230:~$ sudo service apparmor restart
qiang@09230:~$ sudo service mysql start
qiang09230:~$
8、验证修改是否生效
drc@iZwz91oq31508figapkas0Z:/data$ mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.28-0ubuntu0.20.04.3 (Ubuntu)
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
mysql> show variables like 'datadir';
+---------------+---------------------+
| Variable_name | Value |
+---------------+---------------------+
| datadir | /data/mysql/mysql/ |
+---------------+---------------------+
1 row in set (0.00 sec)
mysql>
验证修改成功。