
Introduction
In MySQL, you can backup your data either by using a logical or a physical backup. The former makes MySQL dump file. On the other hand, a physical MySQL backup is a raw copy of all files and directories containing the database information. You can create MySQL logical backups by using mysqldump or by installing automated tools such as automysqlbackup. In this guide, you'll create a physical MySQL backup.
Prerequisites
Before you begin, ensure you have a non-root user with sudo privileges and a MySQL database server.
Locate the Data Directory
Log in to MySQL server with your root password.
$ sudo mysql -u root -pThe following SQL will reveal the data directory of your MySQL instance.
mysql> select @@datadir;The output is similar to this.
+-----------------+ | @@datadir | +-----------------+ | /var/lib/mysql/ | +-----------------+ 1 row in set (0.00 sec)
Alternate method
Locate the MySQL data path without logging to the MySQL server.
$ sudo mysqld --verbose --help | grep ^datadirThe output is similar to this.
datadir /var/lib/mysql/Backup the Database
Stop the MySQL service.
$ sudo systemctl stop mysqlCreate a directory to store the MySQL file backup. Create a parent directory and sub-directories with the current date. This naming scheme allows you to determine the last backup date.
$ sudo mkdir -p /var/mysql_backups/2020_07_13_backupCopy the database file with
cp.$ sudo cp -R /var/lib/mysql/. /var/mysql_backups/2020_07_13_backupStart the database server.
$ sudo systemctl start mysql
Restore the Database
Stop the MySQL service.
$ sudo systemctl stop mysqlRename the current MySQL data directory. This step preserves a backup copy of the current state.
$ sudo mv /var/lib/mysql /var/lib/mysql_oldCreate a new MySQL data directory.
$ sudo mkdir /var/lib/mysqlRestore the MySQL backup.
$ sudo cp -R /var/mysql_backups/2020_07_13_backup/. /var/lib/mysqlChange the ownership of
/var/lib/mysqlto themysqluser.$ sudo chown -R mysql:mysql /var/lib/mysqlStart the database server.
$ sudo systemctl start mysql
Test the Backup
Test the backup by logging to the MySQL server as root.
$ sudo mysql -u root -pVerify the database schema is correct.
mysql> SHOW DATABASES;Your databases are displayed. For example:
+--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+
Conclusion
In this guide, you've created a physical backup of your MySQL database. This method is ideal for large databases and makes restoration easier when reinstalling a database server.