Platinum Partner
coldfusion,cloud,mysql,tutorial,aws

How to Schedule MySQL Database Backups to Amazon S3

I've recently launched a site using MySQL as a database, and wanted to be able to schedule database backups to Amazon S3

I did a bit of searching and found Ray Camden's blog post from way back in 2006 about using cfexecute to create the MySQL backups. I took what Ray had done and added some new functionality so that each database is backed up into a seperate file, zipped and then uploaded to Amazon S3.

Here is by final script, which is called via a scheduled task.

<!--- MySQL backup details --->
<cfset path = "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqldump">
<cfset zipdir = "C:\backup\mysql\">
<cfset backupdir = zipdir & "databases\">
<cfset username = "root">
<cfset password = "letmein">

<cfset datetime = DateFormat(Now(), "YYYYMMDD" ) & TimeFormat(Now(), "HHMMSS" )>
<cfset zipfilename = datetime & "_dbbackup.zip">

<!--- get MySQL databases --->
<cfquery name="qDatabases" username="#username#" password="#password#">
  SHOW DATABASES;
</cfquery>

<!--- loop and backup each database --->
<cfloop query="qDatabases">
  <cfset filename = "#datetime#_#qDatabases.Database#.sql">
  <cfexecute name='"#path#"'
    arguments=' --user=#username# --password=#password# --databases --log-error="#zipdir#" #qDatabases.Database#'
    outputfile='#backupdir##filename#'
    >
  </cfexecute>
  <cfoutput>backup: "#backupdir##filename#" successful<br></cfoutput>
</cfloop>

<!--- zip backups --->
<cfzip action="zip" source="#backupdir#" 
  file="#zipdir##zipfilename#" 
  overwrite="true">
  
<!--- upload to Amazon S3 --->
<cffile action="copy" 
  source="#zipdir##zipfilename#" 
  destination="s3://MyBucket/backup/">

My Amazon S3 credentials are defined in Application.cfc like so:

component
{
  this.name = Hash( getDirectoryFromPath( getCurrentTemplatePath() ) );
  // S3 details
  this.s3.accessKeyId = "A1B1C1D1E1F1G1H1;
  this.s3.awsSecretKey = "a1b2c3d4e5/A1B1C1D1E1F1G1H/1A2B";
}

 

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}