How do I backup MySQL in Linux?

1.  Copying from the mysql directory

 By default, MySQL databases on servers that use Linux are stored in the following directory:

 /var/lib/mysql/

 If you shut down the mysqld service first, you can copy your databases to an example /backup directory using the following command:

 cp –Rp /var/lib/mysql/*.* /backup

The –R switch for the cp command means recursive, which you want to use because each database is in a separate directory.  The –p switch is for permissions, which will maintain the permissions of what is copied.

You generally want to shutdown the mysqld service before using the above method because if a database is copied while it is actively being used, the resulting backup will be corrupt and therefore worthless.  If you are certain none of the databases are not being used at the time, you can use the above command.

2. The mysqldump command

The mysqldump command lets you back up both individual databases and all databases on a server without having to shutdown the mysqld service.  Because of this ability to make backups while still keeping databases online, this method is preferred.

Individual databases

An example command that would let you back up a database named example to the directory /backup while logged in as root is as follows:

mysqldump example > /backup/example_backup.sql

Unless it is a small database, it is recommended that you then compress the resulting database backup in order to reduce the amount of time necessary to transfer the backup.  The following command would compress the backup of the example database:

tar czvf /backup/example_backup.tar.gz /backup./example_backup.sql

All databases 

If you have numerous databases and backing all of them up individually would be too time consuming, the following command will backup all MySQL databases on your server to the /backup directory:

mysqldump -A > /backup/databases.sql(or --all-databases)

The –A switch (“-all-databases” performs the same function) will dump any and all databases on the server.

  • 2 Users Found This Useful
Was this answer helpful?

Related Articles

Connecting to your VPS via VNC

This knowledge base article will explain how you can connect to your VNC enabled Linux VPS....

How to set reverse DNS (rDNS)

At the moment you need to open a Helpdesk ticket and provide your IP and PTR record you want set,...

My SSH shows "-bash-*". How to change?

When a Xen VPS is delivered and you login for the first time you might see something similar to...

Installing OpenVPN on OpenVZ VPS (CentOS)

You must enable tun/tap and or PPP directly from inside VPS Manager under "settings" tab. then...

How to add website via webmin

This is a great tutorial how you can add new domain/website using webmin....