2019-01-24 13:01:13 +01:00
|
|
|
![Snel.com](https://static.snel.com/logo/Snel.com-Logo.png)
|
2019-01-24 13:00:46 +01:00
|
|
|
|
|
|
|
# MySQL / MariaDB backup script #
|
|
|
|
|
2019-01-24 13:29:29 +01:00
|
|
|
Allows you to create and restore local MySQL / MariaDB backups.
|
|
|
|
|
|
|
|
# Requirements #
|
|
|
|
|
2019-01-25 13:20:09 +01:00
|
|
|
Requires a /root/.my.cnf file which contains credentials so the user root can login to the MySQL / MariaDB server with sufficient privileges
|
|
|
|
without entering a password. Example /root/.my.cnf contents:
|
2019-01-24 13:29:29 +01:00
|
|
|
|
|
|
|
```
|
|
|
|
[client]
|
|
|
|
user=root
|
|
|
|
password=mysecretpassword
|
|
|
|
```
|
|
|
|
|
|
|
|
Don't forget to change the permissions:
|
|
|
|
```
|
|
|
|
sudo chmod 600 /root/.my.cnf
|
|
|
|
```
|
|
|
|
|
|
|
|
Test if it works with:
|
|
|
|
```
|
|
|
|
PING=$(sudo mysqladmin ping 2>/dev/null)
|
|
|
|
if [ "$PING" != "mysqld is alive" ]; then
|
|
|
|
clear && echo "Error: Unable to connect to MySQL Server!"
|
|
|
|
else
|
|
|
|
clear && echo "Successfully connected to the MySQL server!"
|
|
|
|
fi
|
|
|
|
```
|
2019-01-24 13:00:46 +01:00
|
|
|
|
|
|
|
## Install script ##
|
|
|
|
|
|
|
|
```
|
2019-01-24 13:29:29 +01:00
|
|
|
sudo wget -O /usr/local/sbin/backup_mysql.sh https://git.snel.com/snelcom/backup-mysql/raw/branch/master/backup_mysql.sh
|
|
|
|
sudo chmod 700 /usr/local/sbin/backup_mysql.sh
|
2019-01-24 13:00:46 +01:00
|
|
|
```
|
|
|
|
|
|
|
|
## Install cronjob ##
|
|
|
|
|
2019-01-24 13:29:29 +01:00
|
|
|
This will add a cronjob to root which will run this script daily at 0:10 am. Adjust as necessary.
|
|
|
|
|
|
|
|
```
|
|
|
|
(sudo crontab -l 2>/dev/null; sudo echo '10 0 * * * test -x /usr/local/sbin/backup_mysql.sh && /usr/local/sbin/backup_mysql.sh') | sudo crontab -
|
|
|
|
```
|
2019-01-24 13:00:46 +01:00
|
|
|
|
|
|
|
## Recover database ##
|
|
|
|
|
2019-01-24 13:29:29 +01:00
|
|
|
Assuming you want to restore mytestdb from your backups made on 20190121-1540:
|
|
|
|
|
|
|
|
```
|
|
|
|
DB='mytestdb'
|
|
|
|
BACKUPDIR='/var/backup/mysql/20190121-1540'
|
|
|
|
sudo mysql -e "CREATE DATABASE IF NOT EXISTS ${DB}"
|
|
|
|
sudo -i bash -c 'for table in ${BACKUPDIR}/${DB}/*; do gunzip -c $table | mysql ${DB}; done'
|
|
|
|
```
|