Backing Up Laravel Homestead Databases

    $ July 13, 2016

    Laravel Homestead is an awesome tool for building Laravel sites. However, sometimes it would be nice if when you did a vagrant destory you wouldn’t lose all of the information in your databases. Or in my case, if you database crashes and you can’t get it back up, it would be great if you had a database backup to restore from.

    Thankfully it’s relatively simple to create a database backup cron on Homestead (v0.5.0 at time of writing). First we need to add a folder mapping as a location to store our backups so they persist on our host machine. To do this edit your ~/.homestead/Homestead.yaml (or your local Homestead.yaml if you use a per-project installation):

    folders:
      - map: "~/HomesteadBackup"
        to: /home/vagrant/backup
    

    Make sure to vagrant reload — provision to create the new backup location on the VM.

    Then we can use Homestead’s after.sh provisioning file to create a daily cron to run our backup script: Edit ~/.homestead/after.sh and add the following script:

    #!/bin/sh
    # If you would like to do some extra provisioning you may
    # add any commands you wish to this file and they will
    # be run after the Homestead machine is provisioned.
    if [ ! -f /etc/cron.daily/database-backup ]; then
        sudo bash -c "cat > /etc/cron.daily/database-backup" <<EOL
    #!/bin/bash
    # Database credentials
    user="homestead"
    password="secret"
    # Other options
    backup_path="/home/vagrant/backup"
    date=\`date +%Y-%m-%d\`
    # Dump database into SQL file
    databases=\`mysql -u \$user -p\$password -e "SHOW DATABASES;" | grep -Ev "(mysql|information_schema|performance_schema|Database|sys)"\`
    for db in \$databases; do
        echo "Backing up database \${db}..."
        mysqldump --force --opt -u \$user -p\$password --databases \$db > "\${backup_path}/\${db}_\${date}.sql"
    done
    # Delete files older than 30 days
    find \$backup_path/* -mtime +30 -exec rm {} \;
    EOL
        sudo chmod +x /etc/cron.daily/database-backup
    fi
    

    This script will create a daily cron that will backup each of your databases, in separate SQL files, in the specified backup location. It will also delete backups older than 30 days to save space.

    To install the new backup script you simply need to run vagrant provision.