You might want to try Google Gemini to solve such problems.
When you run a database on a virtual machine, the default disk can quickly fill up. A common and robust solution is to move your database to a separate, larger data disk. This guide walks you through the process, based on a Google Cloud Ubuntu VM, but the steps are applicable to most Linux distributions.
⚠️ IMPORTANT: Before You Begin, Create a Backup! ⚠️ This process involves moving critical files. It is absolutely essential to back up your database and server data before proceeding.
1. Completely Uninstall MySQL
If you are starting with a fresh installation, you can skip this step. If you’ve had a problematic installation, starting with a clean slate is the best way to avoid errors. The purge
command is crucial here as it removes configuration files and the data directory.
sudo systemctl stop mysql
sudo apt-get purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo rm -rf /etc/mysql /var/lib/mysql
2. Re-install MySQL
With a clean system, perform a fresh installation of the MySQL server. It will automatically install to the default location.
sudo apt-get update
sudo apt-get install mysql-server -y
3. Move the Data Directory to the New Disk
This is the most critical step. We will immediately move the freshly installed data directory to your secondary disk.
- Stop the MySQL Service
sudo systemctl stop mysql
- Correct Permissions on the New Disk:
This is a critical step to prevent the service from failing. Ensure the mount point for your second disk (/mnt/data
in this example) has the correct ownership.sudo chown mysql:mysql /mnt/data
- Move the Data and Create a Symbolic LinkThe
rsync
command will copy the data while preserving permissions, and the symbolic link will create a “shortcut” from the default location to the new one, so you don’t have to edit the configuration file.
sudo rsync -av /var/lib/mysql/ /mnt/data/mysql/
sudo mv /var/lib/mysql /var/lib/mysql.bak
sudo ln -s /mnt/data/mysql /var/lib/mysql
- Update the AppArmor PolicySince you’re on an Ubuntu server, the AppArmor security module needs to be told it is okay for MySQL to access the new disk location.
- Open the AppArmor policy file.
sudo nano /etc/apparmor.d/usr.sbin.mysqld
- Go to the very bottom of the file and, just before the closing curly bracket
}
, add a new line to allow access to the new directory./mnt/data/mysql/ r,
- Save the file and then reload the policy.
sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld
- Open the AppArmor policy file.
4. Start MySQL and Verify
Finally, start the MySQL service. It will now use the data on your second disk.
sudo systemctl start mysql
Congratulations! You have successfully moved your MySQL database to a separate data disk, which will allow you to scale your storage without affecting your main disk.