Moving the data dir of MariaDB on CentOS7

You should have root access to the CentOS host and a new target directory ready for the MariaDB data.

For this guide, our new target directory is /data/database.

First, stop MariaDB.

systemctl stop mariadb

Now, copy your existing database directory to the new location. By default, it is /var/lib/mysql. If it’s not there, check the config in /etc/my.cnf and look for the datadir path. We use -r to copy recursively, and -p to preserve the permissions. You could also use rsync.

cp -rp /var/lib/mysql /data/database

Now rename your old datadir so we don’t get confused.

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

Now edit the /etc/my.cnf file. We are changing any instance of the previous datadir of /var/lib/mysql to the new datadir of /data/database/mysql.

[mysqld] datadir = /data/database/mysql socket = /data/database/mysql/mysql.sock ... log_bin = /data/database/mysql/mysql_binary_log [client] port=3306 socket=/data/database/mysql/mysql.sock

Lastly, if you have binary logs on (which you will by default) you’ll need to modify the index file.

Edit the mysql_binary_log.index file, which will now be at /data/database/mysql/mysql_binary_log.index. Again, replace any instance of the previous datadir of /var/lib/mysql to the new datadir of /data/database/mysql. Example:

/var/lib/mysql/mysql_binary_log.000027

becomes

/data/database/mysql/mysql_binary_log.000027

Now start MariaDB.

systemctl start mariadb

Don’t forget to clean up the /var/lib/mysql.bak after you have tested that your database is working.