Skip to content

Backing up MySQL databases automatically with a cron job

Your Ruachost hosting is already backed up automatically with JetBackup. See Restoring files, email and databases using JetBackup. If you also want your own copies, for example every few hours on a busy shop, or to download them elsewhere, a cron job can make them for you.

Putting a password in a cron job is risky, so save it in a private settings file instead.

  1. In cPanel, open File Manager and go to your home folder (not public_html).

  2. Click Settings and tick Show Hidden Files (dotfiles).

  3. Create a file named .my.cnf with:

    [client]
    user=cpaneluser_dbuser
    password="your-database-password"

    Use a database user that has access to the databases you want to back up. See Finding your database details.

  4. Right-click the file, choose Change Permissions, and set it to 600, so only your account can read it.

In File Manager, create a folder named db-backups in your home folder. Keep it outside public_html, so the backups can’t be downloaded from your website.

  1. In cPanel, open Cron Jobs. See Setting up cron jobs in cPanel.

  2. Choose Once Per Day (or another schedule).

  3. In Command, enter (replace cpaneluser_dbname with your database name):

    Terminal window
    /usr/bin/mysqldump --single-transaction --quick cpaneluser_dbname | gzip > $HOME/db-backups/cpaneluser_dbname-$(date +\%F-\%H\%M).sql.gz
  4. Click Add New Cron Job.

The % signs must be written as \% in cron jobs, as shown.

Add a second cron job, once per day, to delete backups older than 7 days:

Terminal window
find $HOME/db-backups -name "*.sql.gz" -mtime +7 -delete

To back up each database to its own file, use this command in Step 3 instead:

Terminal window
for db in $(mysql -N -e "SHOW DATABASES" | grep -v -E "^(information_schema|performance_schema)$"); do /usr/bin/mysqldump --single-transaction --quick "$db" | gzip > $HOME/db-backups/$db-$(date +\%F).sql.gz; done

The database user in .my.cnf needs access to every database.

The next day, open db-backups in File Manager and check a file is there and isn’t 0 bytes. To restore one, unzip it and import it with phpMyAdmin. See Importing a large database.

Was this page helpful?