13.07.2015 Views

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 4 ■ TAKING BACKUPS AND MANAGING DATA4-4. Backing Up MySQLTo back up a MySQL database, you can use the mysqldump command:mysqldump -u root -pPASSWORD --single-transaction --all-databases > databasesbackup.sqlThis will back up all available databases on that server to the file databasesbackup.sql; to specify aparticular database, use the database name in place of –all-databases. If you’re doing this by hand, youcan leave out PASSWORD; the -p option with no argument will ask for the password on the command line.■ Note --single-transaction works for transactional tables (such as InnoDB and BDB), because it will dumpthe state of the database when the command was issued. MyISAM or MEMORY tables, however, could still changestate. For these types of tables, you can instead use the --lock-tables option. Bear in mind that tables fordifferent databases are locked separately, so there could be inconsistencies between databases (if somethingchanged in database 2 while database 1 was locked, for example). For MyISAM tables, another option is to use themysqlhotcopy utility, which is the fastest backup option.However, as with all backups, what you want is to automate it. Save the following script as/etc/cron.daily/mysqlbackup:01 #!/bin/bash02 dir="/usr/local/backups/"03 remotedir="/shared/raid/server_backups"04 mysqldir="${dir}ldap"05 filename="databases_"06 num=`date +%Y%m%d`07 mysqldump -u root -pPASSWORD --single-transaction –all-databases > ${mysqldir}${filename}${num}.ldif08 find $mysqldir -mtime +14 | xargs rm --09 cp $mysqldir/* $remotedirThis script saves a dump of the database in a local directory (${mysqldir}, line 07) and then copies itto a remote directory as well (line 09). The call to date on line 06 will produce files named for the datecreated, such as /var/backups/databasesbackup_20090711.sql, which means that you keep a history ofdatabase backups; line 08 clears out any backups older than two weeks so that you don’t end up overrunwith them.One obvious problem with this is that your MySQL root password is right there in plain text in thefile. Not very secure! A better bet is to create a user with minimal privileges (you can use SELECT, whicheffectively allows the user to view everything, and you can use LOCK TABLES so that the tables can belocked if need be) just for the purposes of backing up. Connect to your MySQL server as root (mysql -uroot -p), and issue this command:102Download at WoweBook.Com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!