How to Change default MySQL Data Directory in Linux

Mostly MySQL uses /var/lib/mysql directory as default data directory for Linux based systems. But if you wanted to change your data folder to another location,Follow the below steps to make all the changes:

Note: Use all the command as per you system settings.

1. Stop MySQL

Before making any changes, first make sure to stop mysql service

service mysqld stop

2. Create New MYSQL directory where you want to move your data.

mkdir /home/mysql

3. Change Data Directory

Now move default MySQL data directory (/var/lib/mysql) to other location as per your requirement. Also set the required MySQL ownership on new directory location.

mv /var/lib/mysql /home/mysql
chown mysql.mysql /home/mysql

Now edit MySQL default configuration file /etc/my.cnf and update values of datadir and socket variable.

Change From:
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

Change To: 
datadir=/home/mysql
socket=/home/mysql/mysql.sock

4. Start MySQL

After making all above changes. finally start MySQL service. Now it will use new data directory path.

Change From:
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

Change To: 
datadir=/data/mysql
socket=/data/mysql/mysql.sock

After making all above changes. Start MySQL service. Now it will use new data directory path.

service mysqld start

Once this is done check your websites and make sure that everything is working fine. Just in case If you face any issue during MySQL startup check mysql log file /var/log/mysqld.log for any errors.