Recover MySQL Database After Page Corruption
When a server outage happens MySQL may not shut down cleanly and upon restart it may fail with the following error:
2022-07-09T01:29:38.886478Z 0 [ERROR] InnoDB: Database page corruption on disk or a failed file read of page [page id: space=0, page number=505]. You may have to recover from a backup.
CAUTION Please ensure backing up a MySQL database directory before proceeding with the below steps.
First we need to start MySQL in recovery mode by the setting the following configuration in /usr/local/etc/mysql/my.cnf:
innodb_force_recovery = 1
Once MySQL is up we can dump MySQL databases using following command:
mysqldump -u root -p --all-databases --triggers --routines --event --set-gtid-purged=off > all_databases.sql
We can also select to dump a particular database we would like to restore:
mysqldump -u root -p --databases mysql > mysql.sql
After mysqldump completes we need to shut down MySQL and back up /var/db/mysql directory.
Now we need to switch off MySQL recovery mode in /usr/local/etc/mysql/my.cnf:
innodb_force_recovery = 0
After this we need the MySQL server to create a fresh database structure using following command:
mysqld_safe --skip-grant-tables --initialize &
Once the MySQL server is up we can restore our databases using following command:
mysql < all_databases.sql
Finally shut down the MySQL server and restart it normally.