Wednesday, June 7, 2017

Changing MySQL Data Disk/Directory on Linux


First stop Mysql service

/etc/init.d/mysqld stop
rename the mysql directory
mv /var/lib/mysql /var/lib/mysql_old

Mount a secondary disk as data disk, I have mounted /disk2 to my /dev/sdb

create a folder ‘mysql’ in destination disk/partition

copy whole Mysql data directory to ‘mysql’ in preserve mode

cp –pr /var/lib/mysql/ /disk2/mysql

-p means preserve the specified attributes (default: mode, ownership, timestamps)


then create a symbolic link from new data directory to old data directory

ln -s /disk2/mysql/ /var/lib/mysql/

Change permissions on /var/lib/mysql.

chown -R mysql:mysql /var/lib/mysql

If AppArmor is not enabled you do not need to do below. But it is recommended to have AppArmor enabled for security. Follow below steps to allow mysql access through AppArmor:

vim /etc/apparmor.d/usr.sbin.mysqld and add the data directory to it
/disk2/database/mysql/** rwk,
 /disk2/database/mysql/ r,

Now start Mysql service
/etc/init.d/mysqld start
If its working properly then delete each file and folder from old data directory

cd /var/lib/mysql_old rm –rf  *

NOTE: Please take a backup of your MySQL databases before attempting migration.