The profile

One, the introduction

2. Full backup

3. Restore full backup

Incremental backup

5. Restore incremental backup

6. Regular backup

Implementation in Docker

A,The introduction

After the launch of the product, our data is very important, not the slightest mistake should be made, we should be fully prepared, even if one day it will be hacked or malicious deletion, then GG. So we need to do full backup and incremental backup to our online database regularly. For example, perform incremental backup once a day and full backup once a week.

Making address:


     
  1. https://github.com/zonezoen/MySQL_backup

Copy the code

2. Full backup


     
  1. /usr/bin/mysqldump -uroot -p123456  --lock-all-tables --flush-logs test > /home/backup.sql

Copy the code

As shown in the previous code, the function is to make a full backup of the Test database. The MySQL user name is root, and the password is 123456. The backup file path is /home. Of course, this path can be changed according to personal preference. The name of the backup file is backup.sql

Parameter – flush-logs: use a new log file to record subsequent logs;

Parameter – lock-all-tables: locks all databases;

Here is the script file I used:

Script file function is not very complicated, first of all, variable assignment. Then back up the database, then go to the directory where the backup files reside, and then compress the backup files. The penultimate third line is to use nodeJS to upload the backup file to the seven ox cloud, here is not too much description, and the topic of this article is not consistent, want to see the specific implementation can view GitHub source code.


     
  1. #! /bin/bash

  2. Create the following directories before using them

  3. Get the current time

  4. date_now=$(date "+%Y%m%d-%H%M%S")

  5. backUpFolder=/home/db/backup/mysql

  6. username="root"

  7. password="123456"

  8. db_name="zone"

  9. Define the backup file name

  10. fileName="${db_name}_${date_now}.sql"

  11. Define the backup file directory

  12. backUpFileName="${backUpFolder}/${fileName}"

  13. echo "starting backup mysql ${db_name} at ${date_now}."

  14. /usr/bin/mysqldump -u${username} -p${password}  --lock-all-tables --flush-logs ${db_name} > ${backUpFileName}

  15. Go to the backup file directory

  16. cd ${backUpFolder}

  17. # compress backup files

  18. tar zcvf ${fileName}.tar.gz ${fileName}

  19. # use nodejs to upload backup file other place

  20. #NODE_ENV=$backUpFolder@$backUpFileName node /home/tasks/upload.js

  21. date_end=$(date "+%Y%m%d-%H%M%S")

  22. echo "finish backup mysql database ${db_name} at ${date_end}."

Copy the code

3. Restore full backup


     
  1. mysql -h localhost -uroot -p123456 < bakdup.sql

Copy the code

or


     
  1. mysql> source /path/backup/bakdup.sql

Copy the code

Well, restore full backup is only two sentences, it seems that there is no need to say anything more. By the way, after restoring the full backup, the incremental backup after the full backup is also restored to the database.

Incremental backup

Before performing incremental backup, check the configuration file to check whether Logbin is enabled. For incremental backup, you must enable Logbin. First, go to the myslq command line and type the following command:


     
  1. show variables like '%log_bin%';

Copy the code

If the following command output is displayed, the function is disabled


     
  1. mysql> show variables like '%log_bin%';

  2. +---------------------------------+-------+

  3. | Variable_name                   | Value |

  4. +---------------------------------+-------+

  5. | log_bin                         | OFF   |

  6. | log_bin_basename                |       |

  7. | log_bin_index                   |       |

  8. | log_bin_trust_function_creators | OFF   |

  9. | log_bin_use_v1_row_events       | OFF   |

  10. | sql_log_bin                     | ON    |

  11. +---------------------------------+-------+

Copy the code

Modify the MySQL configuration items to the following code snippet: vim/etc/MySQL/MySQL. Conf., d/mysqld. CNF


     
  1. # Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.

  2. #

  3. # This program is free software; you can redistribute it and/or modify

  4. # it under the terms of the GNU General Public License as published by

  5. # the Free Software Foundation; version 2 of the License.

  6. #

  7. # This program is distributed in the hope that it will be useful,

  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of

  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

  10. # GNU General Public License for more details.

  11. #

  12. # You should have received a copy of the GNU General Public License

  13. # along with this program; if not, write to the Free Software

  14. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

  15. #

  16. # The MySQL  Server configuration file.

  17. #

  18. # For explanations see

  19. # http://dev.mysql.com/doc/mysql/en/server-system-variables.html

  20. [mysqld]

  21. pid-file    = /var/run/mysqld/mysqld.pid

  22. socket        = /var/run/mysqld/mysqld.sock

  23. datadir        = /var/lib/mysql

  24. #log-error    = /var/log/mysql/error.log

  25. # By default we only accept connections from localhost

  26. # bind - address = 127.0.0.1

  27. # Disabling symbolic-links is recommended to prevent assorted security risks

  28. symbolic-links=0

  29. #binlog setting, enable incremental backup key

  30. log-bin=/var/lib/mysql/mysql-bin

  31. server-id=123454

Copy the code

After the modification, restart the mysql service and enter:


     
  1. show variables like '%log_bin%';

Copy the code

The status is as follows:


     
  1. mysql> show variables like '%log_bin%';

  2. +---------------------------------+--------------------------------+

  3. | Variable_name                   | Value                          |

  4. +---------------------------------+--------------------------------+

  5. | log_bin                         | ON                             |

  6. | log_bin_basename                | /var/lib/mysql/mysql-bin       |

  7. | log_bin_index                   | /var/lib/mysql/mysql-bin.index |

  8. | log_bin_trust_function_creators | OFF                            |

  9. | log_bin_use_v1_row_events       | OFF                            |

  10. | sql_log_bin                     | ON                             |

  11. +---------------------------------+--------------------------------+

Copy the code

Now that we’re ready, we’re ready to learn about incremental backup.

Check the mysql_bin.000* log file currently in use,


     
  1. show master status;

Copy the code

The status is as follows:


     
  1. mysql> show master status;

  2. +------------------+----------+--------------+------------------+-------------------+

  3. | File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |

  4. +------------------+----------+--------------+------------------+-------------------+

  5. | mysql-bin.000015 |      610 |              |                  |                   |

  6. +------------------+----------+--------------+------------------+-------------------+

Copy the code

The name of the log file is mysql-bin.000015.

The current database has the following data:


     
  1. mysql> select * from users;

  2. +-------+------+----+

  3. | name  | sex  | id |

  4. +-------+------+----+

  5. | zone  | 0    |  1 |

  6. | zone1 | 1    |  2 |

  7. | zone2 | 0    |  3 |

  8. +-------+------+----+

Copy the code

We insert a piece of data:


     
  1. insert into `zone`.`users` ( `name`, `sex`, `id`) values ( 'zone3', '0', '4');

Copy the code

View the effect:


     
  1. mysql> select * from users;

  2. +-------+------+----+

  3. | name  | sex  | id |

  4. +-------+------+----+

  5. | zone  | 0    |  1 |

  6. | zone1 | 1    |  2 |

  7. | zone2 | 0    |  3 |

  8. | zone3 | 0    |  4 |

  9. +-------+------+----+

Copy the code

‘We execute the following command to use the new log file:


     
  1. mysqladmin -uroot -123456 flush-logs

Copy the code

The log file changes from mysql-bin.000015 to mysql-bin.000016, and mysql-bin.000015 records the log of the insert command. The code above looks like this:


     
  1. mysql> show master status;

  2. +------------------+----------+--------------+------------------+-------------------+

  3. | File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |

  4. +------------------+----------+--------------+------------------+-------------------+

  5. | mysql-bin.000016 |      154 |              |                  |                   |

  6. +------------------+----------+--------------+------------------+-------------------+

Copy the code

So by now, you’ve actually done incremental backup.

5. Restore incremental backup

Now delete the inserted data as follows:


     
  1. delete from `zone`.`users` where `id`='4'

  2. mysql> select * from users;

  3. +-------+------+----+

  4. | name  | sex  | id |

  5. +-------+------+----+

  6. | zone  | 0    |  1 |

  7. | zone1 | 1    |  2 |

  8. | zone2 | 0    |  3 |

  9. +-------+------+----+

Copy the code

Select * from mysql-bin.000015;


     
  1. mysqlbinlog /var/lib/mysql/mysql-bin.000015 | mysql -uroot -p123456 zone;

Copy the code

The mysql_bin file that needs to be restored is specified with user name root, password 123456, and database name zone. The effect is as follows:


     
  1. mysql> select * from users;

  2. +-------+------+----+

  3. | name  | sex  | id |

  4. +-------+------+----+

  5. | zone  | 0    |  1 |

  6. | zone1 | 1    |  2 |

  7. | zone2 | 0    |  3 |

  8. | zone3 | 0    |  4 |

  9. +-------+------+----+

Copy the code

OK, the whole process of incremental backup is here, so how do we write it as a script file, the code is as follows:


     
  1. #! /bin/bash

  2. Create the following directories before using them

  3. BakDir=/usr/local/work/backup/daily

  4. Mysql > create mysql-bin.00000* from mysql-bin.00000

  5. BinDir=/var/lib/mysql

  6. Mysql data directory

  7. LogFile=/usr/local/work/backup/bak.log

  8. BinFile=/var/lib/mysql/mysql-bin.index

  9. Mysql index file path to the data directory

  10. mysqladmin -uroot -p123456 flush-logs

  11. This is used to generate a new mysql-bin.00000* file

  12. # wC-l Count rows

  13. Awk simply means reading a file line by line, slicing each line with a space as the default separator, and then parsing it.

  14. Counter=`wc -l $BinFile |awk '{print $1}'`

  15. NextNum=0

  16. This for loop is used to compare $Counter and $NextNum to determine if the file exists or is up to date

  17. for file in `cat $BinFile`

  18. do

  19.    base=`basename $file`

  20.    echo $base

  21. /mysql-bin.000005; /mysql-bin.000005; /

  22.    NextNum=`expr $NextNum + 1`

  23.    if [ $NextNum -eq $Counter ]

  24.    then

  25.        echo $base skip! >> $LogFile

  26.    else

  27.        dest=$BakDir/$base

  28.        if(test -e $dest)

  29. #test -e check whether the target file exists, write exist! To $LogFile

  30.        then

  31.            echo $base exist! >> $LogFile

  32.        else

  33.            cp $BinDir/$base $BakDir

  34.            echo $base copying >> $LogFile

  35.         fi

  36.     fi

  37. done

  38. Echo 'date +"%Y %m %d %H:% m :%S"' $Next Bakup succ! >> $LogFile

  39. # NODE_ENV = $backUpFolder @ $backUpFileName/root /. NVM/versions/node/v8.11.3 / bin/node/usr/local/work/script/upload. Js

Copy the code

6. Regular backup

Run the following command to go to the page for editing scheduled tasks:


     
  1. crontab -e

Copy the code

Add the following command to execute the backup script every minute, and the crontab rules are separate articles that are not relevant to the topic of this article.


     
  1. * * * * * sh /usr/your/path/mysqlbackup.sh

Copy the code

Implementation in Docker

Implementation in Docker, in fact, is much worse, I will not repeat the above steps again, I will directly show you the pit I encountered in Docker.

1. Install VIm

I am using the official image of MySQL, docker-mysql image is used in Debian system, its version is older, there is no vim. First we need to execute the following code to install Vim:


     
  1. apt-get update

  2. apt-get install vim

Copy the code

After installed vim, can happily editor vim/etc/mysql/mysql. Conf. D/mysqld. CNF. I forgot to mention that this file cannot be mapped to the container, because the container itself contains the file.

2. Change the time zone

When we are backing up the database, there is a time factor, but the Docker container defaults to +0 time zone, while we are +8 time zone, we just map the host time zone file to it.


     
  1. -v /etc/localtime:/etc/localtime:ro

Copy the code

Can also modify the time zone through into the container, it depends on personal choice, specific modification method blog: http://coolnull.com/235.html

3. Perform regular backup

How do you implement a scheduled backup in a container? Some people say, crontab? If you think so, there is no crontab in the official docker-mysql mirror. Then someone said, why don’t we just install a Crontab? But Docker encourages a “one process per container” approach. So after a fruitless search, I thought, why don’t we just assign the scheduled tasks to our host? Having the host machine periodically send commands into the container serves our purpose.

Run the following command to go to the page for editing scheduled tasks:


     
  1. crontab -e

Copy the code

Add the following command: Execute the backup script every minute


     
  1. * * * * * docker exec ${docker_name} /bin/sh /usr/your/path/mysqlbackup.sh

Copy the code

This article is contributed by Zone, link to the original article, a backend siege lion who loves to write and share. The public zone7 no.