By default, MySQL stores all its data in /var/lib/mysql. This tutorial explains how to safely move the MySQL data directory to a new location (e.g., another disk or partition) on Ubuntu 25.04.

Step 1: Stop the MySQL Service

Before making any changes, stop the MySQL service:


sudo systemctl stop mysql

Step 2: Move the Existing Data Directory

Choose your new location, for example /mnt/data/mysql, and move the current data:


sudo mv /var/lib/mysql /mnt/data/mysql

> This moves all database files including system schemas like mysql and performance_schema.


Step 3: Set Correct Permissions

Ensure MySQL can access the new directory:


sudo chown -R mysql:mysql /mnt/data/mysql

Step 4: Update MySQL Configuration

Edit the MySQL configuration file:


sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Find the line:


datadir = /var/lib/mysql

Change it to:


datadir = /mnt/data/mysql

Save and exit.


Step 5: (If AppArmor is Enabled) Add Access Rules

AppArmor may block MySQL from accessing the new path.

Edit AppArmor profile for MySQL:


sudo nano /etc/apparmor.d/usr.sbin.mysqld

Add these lines before the closing }:


/mnt/data/mysql/ r,
/mnt/data/mysql/** rwk,

Then reload AppArmor:


sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld

Step 6: Fix MySQL Socket Directory (Optional)

If needed, recreate the MySQL socket directory:


sudo mkdir -p /var/run/mysqld
sudo chown mysql:mysql /var/run/mysqld

Step 7: Restart MySQL


sudo systemctl start mysql

Step 8: Verify the New Data Directory

Check that MySQL is using the new path:


mysql -u root -p -e "SHOW VARIABLES LIKE 'datadir';"

You should see:


+---------------+------------------+
| Variable_name | Value            |
+---------------+------------------+
| datadir       | /mnt/data/mysql/ |
+---------------+------------------+