How to move MySQL database to another drive

1 min read 246 words

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags