Reading Time: < 1 minute

We need to change the default data directory /var/lib/mysql to a different location. Now we will see how to change the default MySQL / MariaDB data directory to a different path on a CentOS/RHEL 7 server.
The new directory in /data/techrunnr/mysql-data and this directory should have ownership of mysql:mysql

 

mkdir  /data/techrunnr/mysql-data

chown -R mysql:mysql  /data/techrunnr/mysql-data

1. Find the current default data directory using the following command.

# mysql -u root -p 

MariaDB [(none)]>select @@datadir;

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

Now we can see default directory is /var/lib/mysql/

2. Copy MySQL data to a new location

First, we need to stop the MariaDB service

sudo systemctl stop mariadb

sudo systemctl status mariadb

Output

Dec 1 15:11:11 mysql systemd[1]: Stopped MariaDB database server.

Now Database is stopped, now we will copy the data to a new location through rsync.

sudo rsync -av /var/lib/mysql  /data/techrunnr/mysql-data

Once rsync is complete, rename the folder.

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

3.Configure New Mysql Data Directory

Will edit my.cnf file to reflect the new directory changes.

check for [mysqld] and [client] to make the changes.

 [mysqld]:
datadir= /data/techrunnr/mysql-data
socket= /data/techrunnr/mysql-data/mysql.sock

 [client]:
port=3306
socket= /data/techrunnr/mysql-data/mysql.sock

Then save the changes.

Change the SELinux Context to Data Directory

Now need to add new /data/techrunnr/mysql-data before starting Maria DB.

semanage fcontext -a -t mysqld_db_t "/data/techrunnr/mysql-data(/.*)?"
 restorecon -R  /data/techrunnr/mysql-data

Now start the mariadb service

sudo systemctl start mariadb
sudo systemctl status mariadb

Now we will check the changes are working or not.

 

MariaDB [(none)]>select @@datadir;

Output
+-----------------+
| @@datadir       |
+-----------------+
| /data/techrunnr/mysql-data/ |
+-----------------+
1 row in set (0.00 sec)

 

Once all are verified and existing data is available, we can remove the backup data directory by rm -Rf /var/lib/mysql.bak

 

 

 

© 2019, Techrunnr. All rights reserved.

#1
#2
#3
Questions Answered
Articles Written
Overall Points

0 Comments

Leave a Reply