Posterous theme by Cory Watilo

How to migrate a MySQL database to a different partition on Ubuntu

Hi techies! I ran into this problem of having the main server partition almost full because of a huge MySQL database. I assume that we're using the innodb engine and that we're running MySQL with the innodb_file_per_table option. The proposed solution I'm describing is to migrate the huge database on a new partition while keeping all the other databases and the MySQL files in the main partition. Here are the steps to achieve the migration properly in a Ubuntu box.

Assuming that the MySQL data directory is located in /var/lib/mysql, our new partition in /vol, and that the huge database is named Metrics.

# First let's shut down MySQL.
/etc/init.d/mysql stop;
# The directory /var/lib/mysql/Metrics contains everything related to the database Metrics. We relocate it.
mv /var/lib/mysql/Metrics /vol/Metrics;
# We create the symlink from the main data directory to the new partition where the database is relocated.
ln -s /vol/Metrics /var/lib/mysql/Metrics;

At this point we could start again mysql and try to use the Metrics database, but we'll most certainly get this error:
ERROR 1018 (HY000): Can't read dir of './Metrics' (errno: 13)
What it means is that MySQL doesn't get the appropriate permission to read in /vol/Metrics. By checking permissions we'll see that everything is ok, but it's without counting on AppArmor. AppArmor is a software running on Ubuntu which prevents some applications like mysqld from accessing the complete filesystem to increase security. We thus have to add new paths that mysqld needs to access in /etc/apparmor.d/usr.sbin.mysqld.

Here is our /etc/apparmor.d/usr.sbin.mysqld file. 

Let's pay attention to the two added lines near the end of the file:

/vol/Metrics/ rw,
/vol/Metrics/* rw,

Finally let's restart AppArmor and then restart MySQL.

/etc/init.d/apparmor/restart;
/etc/init.d/mysql/start;

The database relocation is a success, congrats!