How to Move MySQL Database to Another Drive

Step 1:

Login to your MySQL server, enter your password when prompted:

mysql -u root -p

Find out where the data directory is located:

mysql> select @@datadir;
Output
+-----------------+
| @@datadir       |
+-----------------+
| /var/lib/mysql/ |
+-----------------+
1 row in set (0.00 sec)

Step 2:

Now you can stop the server and check the status:

sudo systemctl stop mysql
sudo systemctl status mysql

It’s time to make a copy to your new mount location:

sudo rsync -av /var/lib/mysql /mnt/new-volume-01

Remember to create a backup of the original data in case you need to revert at a later stage:

sudo mv /var/lib/mysql /var/lib/mysql.bak

Step 3:

Edit the MySQL configuration to update the datadir to the new location:

sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf

Find the datadir key and swap the value with your new mount path:

...
datadir=/mnt/new-volume-01/mysql
...

Step 4:

Update AppArmor to point to a new location:

sudo vi /etc/apparmor.d/tunables/alias

Create a new line at the bottom that references your new mount path, aliased back to /var/lib/mysql.

...
[label /etc/apparmor.d/tunables/alias]
alias /var/lib/mysql/ -> /mnt/new-volume-01/mysql/,
...

Restart AppArmor to pull in the new configuration.

sudo systemctl restart apparmor

Step 5:

Start the MySQL server for changes to take effect.

sudo systemctl start mysql
sudo systemctl status mysql

Login to MySQL again to verify it is using the new directory:

mysql -u root -p

Re-run the command from before to verify:

mysql> select @@datadir;
Output
+---------------------------+
| @@datadir                 |
+---------------------------+
| /mnt/new-volume-01/mysql/ |
+---------------------------+
1 row in set (0.00 sec)