mysqllinuxbackup

Automatically Backup MySQL database on linux server


I need a script that automatically makes a backup of a MySql Database. I know there are a lot of posts and scripts out there on this topic already but here is where mine differs.

  1. The script needs to run on the machine hosting the MySql database (It is a linux machine).
  2. The backups must be saved onto the same server that the database is on.
  3. A backup needs to be made every 30 minutes.
  4. When a backup is older than a week it is deleted unless it is the very first backup created that week. i.e out of these backups backup_1_12_2010_0-00_Mon.db, backup_1_12_2010_0-30_Mon.db, backup_1_12_2010_1-00_Mon.db ... backup_7_12_2010_23-30_Sun.db etc only backup_1_12_2010_0-00_Mon.db is kept.

Anyone have anything similar or any ideas where to start?


Solution

  • Doing pretty much the same like many people.

    1. The script needs to run on the machine hosting the MySql database (It is a linux machine).
      => Create a local bash or perl script (or whatever) "myscript" on this machine "A"

    2. The backups must be saved onto the same server that the database is on.
      => in the script "myscript", you can just use mysqldump. From the local backup, you may create a tarball that you send via scp to your remote machine. Finally you can put your backup script into the crontab (crontab -e).

    Some hints and functions to get you started as I won't post my entire script, it does not fully do the trick but not far away :

    #!/bin/sh
    ...
    MYSQLDUMP="$(which mysqldump)"   
    FILE="$LOCAL_TARBALLS/$TARBALL/mysqldump_$db-$SNAPSHOT_DATE.sql"  
    $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db > $FILE && $GZIP $GZ_COMPRESSION_LEVEL $FILE   
    
    function create_tarball()
    {
    local tarball_dir=$1
    tar -zpcvf $tarball_dir"_"$SNAPSHOT_DATE".tar.gz" $tarball_dir >/dev/null
    return $?
    }
    
    function send_tarball()
    {
    local PROTOCOLE_="2"
    local IPV_="4"
    local PRESERVE_="p"
    local COMPRESSED_="C"
    local PORT="-P $DESTINATION_PORT"
    local EXECMODE="B"
    
    local SRC=$1
    local DESTINATION_DIR=$2
    local DESTINATION_HOST=$DESTINATION_USER"@"$DESTINATION_MACHINE":"$DESTINATION_DIR
    
    local COMMAND="scp -$PROTOCOLE_$IPV_$PRESERVE_$COMPRESSED_$EXECMODE $PORT $SRC $DESTINATION_HOST &"
    
    echo "remote copy command: "$COMMAND
    [[ $REMOTE_COPY_ACTIVATED = "Yes" ]] && eval $COMMAND
    
    }
    

    Then to delete files older than "date", you can look at man find and focus on the mtime and newer options.

    Edit: as said earlier, there is no particular interest in doing a local backup except a temproray file to be able send a tarball easily and delete it when sent.