How to Change Mysql data directory
Introduction
MySQL stores all database data, tables, indexes, and logs in a default directory known as the data directory (commonly /var/lib/mysql on Linux systems). In many real-world scenarios, administrators need to change this default location—for example, when the system disk is running out of space, for performance optimization, or when separating data storage from system files for better manageability and backups.
Changing the MySQL data directory allows better control over storage resources while ensuring scalability and system efficiency.
Prerequisites
Before changing the MySQL data directory, ensure the following requirements are met:
- Root or sudo access to the server.
- MySQL/MariaDB installed and running properly.
- Sufficient disk space available in the new target directory.
- Proper backup of all existing databases (very important to avoid data loss).
- MySQL service should be stopped during migration to prevent data corruption.
IMPLEMENTATION
We can change mysql data directory by doing the following steps.
+ Stop the mysql service.
#/etc/init.d/mysql stop
+ Create a directory in /home directory (Normally /home contains large disk space)
# mkdir /home/var_mysql
+ Move the mysql data directory to new location i.e., /home/var_mysql
# mv /var/lib/mysql /home/var_mysql
+ Change the permission of this directory to “mysql”.
# chown -R mysql:mysql /home/var_mysql/mysql
+ Create a symlink to /var/lib/mysql.
# ln -s /home/var_mysql/mysql /var/lib/mysql
+ Start mysql service.
# /etc/init.d/mysql start
+ Check the mysql data directory by using ps command. This will show the mysql data directory.
# ps aux | grep mysql
CONCLUSION
Changing the MySQL data directory is a critical administrative task that helps improve storage management, performance, and scalability of database systems. While the process requires careful planning and downtime, following proper steps such as taking backups, updating configuration files, and setting correct permissions ensures a smooth migration. When done correctly, it enhances system organization and supports better long-term database maintenance.
