How to create a backup file of your database and upload it to AWS s3 bucket using Laravel

Data is an essential ingredient for any business, no matter how large or small! Losing data can cost a lot to business so it is important to take backup and keep the data secure. Talking of data backup and security lets take a walk-through of how to create a database backup file and upload rather securely save it to a cloud platform like AWS using Laravel.

Create a Database Backup File

  1. To dump the database and save it to an SQL file, add the following command:
    mysqldump -v -u[user] -h[host] -p[password] [dbName] > [file_path]

    For example, 
    $mysql_dump_command= “mysqldump -v -u{$dbUser} -h{$dbHost} -p{$dbPassword} {$dbName} >  $backupFileUC”;

    where, the variables $dbUser, $dbHost, $dbPassword, $dbName are the config variables (get their values from the env file via config files) and dbBackupFileUC is the name of the file(uncompressed) to be created.

  2. Now to compress the file, we have command gzip -9 -f [filename]. Therefore,
    $gzip_command= "gzip -9 -f $backupFileUC"

  3. Next, to run these commands in the console add,
    use Symfony\Component\Process\Process;
    use Symfony\Component\Process\Exception\ProcessFailedException;

    $mysql_dump_process= Process::fromShellCommandline($mysql_command);
    $run_mysql->mustRun();

    $gzip_process= Process::fromShellCommandline($gzip_command);
    $gzip_process->mustRun();


Upload The File to AWS S3

Amazon s3 setup

  1. To create a new aws account use link: https://portal.aws.amazon.com/billing/signup or login to your account using the link: https://signin.aws.amazon.com/signin



  2. After successfully logging in, create a bucket using steps as below:
    • In navigation bar select Services → S3 (or directly go to the link: https://s3.console.aws.amazon.com/s3/home)
    • Click on the ‘Create Bucket’ and enter the bucket name and region. Make the required settings and create the bucket.
    • Now, go to the bucket and to generate bucket policy go to Permissions → Bucket Policy and find the policy editor as below:



    • Click on policy generator and add details. For uploading the files to bucket, select policy type as ‘S3 Bucket Policy’, service as ‘Amazon S3’ as follows and click on ‘Add Statement’ :



    • Click on ‘Generate Policy’ and on successful policy generation, a pop-up as given below must display the policy details:

Steps for copying the file to s3 using Laravel

  1. Install the s3 package via composer, using command: composer require league/flysystem-aws-s3-v3
  2. Now add the API key and secret key to the .env file of the project. These can be found in ‘My Security Credentials’ from navigation bar.
    AWS_ACCESS_KEY_ID=xxxx
    AWS_SECRET_ACCESS_KEY=xxxx
    AWS_DEFAULT_REGION=region
    AWS_BUCKET=bucket name

  3. To upload the file from local storage to the amazon s3 bucket use the following:
    $copyFIle= Storage::disk('s3')->put( $s3path.’/’.’$fileName, file_get_contents(public_path($localFile)));

    where, $s3Path= folder or pathname in the bucket
    $fileName= save file as name in cloud
    $file= local storage file

So, what the code looks like?

$dbUser = config('database.connections.mysql.username');
$dbPassword = config('database.connections.mysql.password');
$dbHost = config('database.connections.mysql.host');
$dbName = config('database.connections.mysql.database');
        
$dbBackupFolder = storage_path('app/'.config("filesystems.local_db_backup_folder")); //local folder for backup file

$dbBackupFile =  $dbBackupFolder ."https://regurweb.b-cdn.net/dbbackup.sql";    //uncompressed file

$dbBackupFileCompressed = $dbBackupFolder .'https://regurweb.b-cdn.net/dbbackup.sql.gz';               //compressed file

$localFilePath= $dbBackupFile; //local backup file

$s3Folder=  config("filesystems.s3_backup_folder");  //folder or path  for s3 file

//system command to backup database

$mysql_command = "mysqldump -v -u{$dbUser} -h{$dbHost} -p{$dbPassword}   {$dbName} >  $dbBackupFileUC";
        
$gzip_command = "gzip -9 -f $dbBackupFileUC";
     
try {
      $process_mysql = Process::fromShellCommandline($mysql_command);  
      $process_mysql->mustRun();

      $process_gzip = Process::fromShellCommandline($gzip_command);
      $process_gzip->mustRun();
} catch (ProcessFailedException $exception) {
      $errorOcurred= $exception->getMessage();
      Mail::to($systemEmailId)->send(new BackupFileError($errorOcurred));           
            return $this->error($errorOcurred);
      }

      //check if file exists in local       
      $fileFound = file_exists($dbBackupFile);

      if($fileFound == true){
         $copyTos3= Storage::disk('s3')->put($s3Folder .'/dbbackup.' .'.sql.gz', file_get_contents($dbBackupFile));
     }

Thus, Laravel makes it pretty simple and easy to create database backup files and wrap it in the artisan commands. Also, it allows uploading files to s3 with its package flysystem-aws-s3-v3 effortlessly. However, creating a backup of the most important aspect of the business that is data and saving it securely to a cloud like AWS makes it feed much safer and the businessmen can sit back and relax.


Related Post

About the Author

Rashika Raina

Rashika is working as Business Development Executive at Regur technology Solution. She has a zeal to learn & grow and passion for work in any competitive situation. Her interest lies in Sales, Marketing Strategies, International Marketing, Business development. Apart from this, she has a good hold in communication, presentation and Market research skills.