+4

Backup Database và toàn bộ vps trong laravel

Đối với lĩnh vực IT thì việc backup dữ liệu là điều vô cùng quan trọng, đối với bất kĩ hệ thống cũng cần có sự backup, vì không ai biết được sẽ có sự cố nào xảy ra đối với hệ thống của chúng ta việc backup ko chỉ dừng lại ở database mà tất cả những cái trong server của chúng ta cũng đều cần phải backup như hình ảnh, source code .... chính vì vậy hôm nay tôi sẽ giới thiệu cho các bạn một phương pháp backup dữ liệu của toàn bộ vps lên dropbox. Trong bài viết này tôi sẽ sử dụng thư viện spatie/laravel-backup:

Cài Đặt:

Chạy lệnh sau

composer require "spatie/laravel-backup:^3.0.0"

Để cài thư viện cần thiết

Đặt vào config/app.php:

'providers' => [
    // ...
    Spatie\Backup\BackupServiceProvider::class,
];

Chạy lệnh

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

Để public config file:

Chúng ra sẽ dc một file config với nội dung như sau:

/config/laravel-backup.php

return [

    'backup' => [

        /*
         * The name of this application. You can use this name to monitor
         * the backups.
         */
        'name' => env('APP_URL'),

        'source' => [

            'files' => [

                /*
                 * The list of directories and files that will be included in the backup.
                 */
                'include' => [
                    base_path(),
                ],

                /*
                 * These directories and files will be excluded from the backup.
                 *
                 * Directories used by the backup process will automatically be excluded.
                 */
                'exclude' => [
                    base_path('vendor'),
                    base_path('node_modules'),
                ],

                /*
                 * Determines if symlinks should be followed.
                 */
                'followLinks' => false,
            ],

            /*
             * The names of the connections to the databases that should be backed up
             * Only MySQL and PostgreSQL databases are supported.
             */
            'databases' => [
                'mysql',
            ],
        ],

        'destination' => [

            /*
             * The filename prefix used for the backup zip file.
             */
            'filename_prefix' => '',

            /*
             * The disk names on which the backups will be stored.
             */
            'disks' => [
                'local',
            ],
        ],
    ],


    /*
     * You can get notified when specific events occur. Out of the box you can use 'mail' and 'slack'.
     * For Slack you need to install guzzlehttp/guzzle.
     *
     * You can also use your own notification classes, just make sure the class is named after one of
     * the `Spatie\Backup\Events` classes.
     */
    'notifications' => [

        'notifications' => [
            \Spatie\Backup\Notifications\Notifications\BackupHasFailed::class         => ['mail'],
            \Spatie\Backup\Notifications\Notifications\UnhealthyBackupWasFound::class => ['mail'],
            \Spatie\Backup\Notifications\Notifications\CleanupHasFailed::class        => ['mail'],
            \Spatie\Backup\Notifications\Notifications\BackupWasSuccessful::class     => ['mail'],
            \Spatie\Backup\Notifications\Notifications\HealthyBackupWasFound::class   => ['mail'],
            \Spatie\Backup\Notifications\Notifications\CleanupWasSuccessful::class    => ['mail'],
        ],

        /*
         * Here you can specify the notifiable to which the notifications should be sent. The default
         * notifiable will use the variables specified in this config file.
         */
        'notifiable' => \Spatie\Backup\Notifications\Notifiable::class,

        'mail' => [
            'to' => 'your@email.com',
        ],

        'slack' => [
            'webhook_url' => '',
        ],
    ],

    /*
     * Here you can specify which backups should be monitored.
     * If a backup does not meet the specified requirements the
     * UnHealthyBackupWasFound event will be fired.
     */
    'monitorBackups' => [
        [
            'name' => env('APP_URL'),
            'disks' => ['local'],
            'newestBackupsShouldNotBeOlderThanDays' => 1,
            'storageUsedMayNotBeHigherThanMegabytes' => 5000,
        ],

        /*
        [
            'name' => 'name of the second app',
            'disks' => ['local', 's3'],
            'newestBackupsShouldNotBeOlderThanDays' => 1,
            'storageUsedMayNotBeHigherThanMegabytes' => 5000,
        ],
        */
    ],


    'cleanup' => [
        /*
         * The strategy that will be used to cleanup old backups. The default strategy
         * will keep all backups for a certain amount of days. After that period only
         * a daily backup will be kept. After that period only weekly backups will
         * be kept and so on.
         *
         * No matter how you configure it the default strategy will never
         * delete the newest backup.
         */
        'strategy' => \Spatie\Backup\Tasks\Cleanup\Strategies\DefaultStrategy::class,

        'defaultStrategy' => [

            /*
             * The number of days for which backups must be kept.
             */
            'keepAllBackupsForDays' => 7,

            /*
             * The number of days for which daily backups must be kept.
             */
            'keepDailyBackupsForDays' => 16,

            /*
             * The number of weeks for which one weekly backup must be kept.
             */
            'keepWeeklyBackupsForWeeks' => 8,

            /*
             * The number of months for which one monthly backup must be kept.
             */
            'keepMonthlyBackupsForMonths' => 4,

            /*
             * The number of years for which one yearly backup must be kept.
             */
            'keepYearlyBackupsForYears' => 2,

            /*
             * After cleaning up the backups remove the oldest backup until
             * this amount of megabytes has been reached.
             */
            'deleteOldestBackupsWhenUsingMoreMegabytesThan' => 5000,
        ],
    ],
];

Trong file config này nó cho phép giữ lại bao nhiêu file backup, loại backup là gì, hay mail nhận khi backup xong:

Chúng ta cần thay đổi một số config như sau:

 'mail' => [
            'to' => 'viblo@gmail.com',  // email nhận khi dữ liệu được backup thành công
        ],
 'disks' => [
        'dropbox',  // lựa chọn nơi lưu trữ, mặc định là local
  ],

Lưu ý có 2 chỗ liên quan đến disks này, cần thay đổi cả 2 cái.

Tiếp theo chúng ta cần cài thư viện: league/flysystem-dropbox (

Chú ý thư viện này yêu cầu php 7 trở lên

composer require league/flysystem-dropbox

Đặt vào trong config/app.php providers nội dung sau:

App\Providers\DropboxFilesystemServiceProvider::class

Backup

Tạo file app/Providers/DropboxFilesystemServiceProvider.php với nội dung như sau:

<?php

namespace App\Providers;

use Storage;
use League\Flysystem\Filesystem;
use Dropbox\Client as DropboxClient;
use League\Flysystem\Dropbox\DropboxAdapter;
use Illuminate\Support\ServiceProvider;

class DropboxFilesystemServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Storage::extend('dropbox', function ($app, $config) {
            $client = new DropboxClient($config['accessToken'], $config['appSecret']);

            return new Filesystem(new DropboxAdapter($client));
        });
    }

    public function register()
    {
        //
    }
}

Vào link https://www.dropbox.com/developers/apps/create để tạo api key:

Tiếp theo lấy secret key và token:

Đặt vào config/filesystems.php nội dung như sau:

'dropbox' => [
 'driver' => 'dropbox',
 'accessToken' => env('DROPBOX_ACCESS_TOKEN'), // access token bên trên
 'appSecret' => env('DROPBOX_APP_SECRET'),  // secrest key
 ]

Để test xem chúng ta setup thành công chưa chạy lệnh sau:

php artisan backup:run

khi chạy sẽ có màn hình như này:

khi chạy xong chúng ta sẽ nhận dc 1 email thế này:

 Great news, a new backup of [your app name] was successfully created on the disk named dropbox.

Application name: [your app name]

Disk: dropbox

Newest backup size: 388.5 MB

Amount of backups: 6

Total storage used: 2.27 GB

Newest backup date: 2017/02/22 18:56:11

Oldest backup date: 2017/02/18 02:05:22 
....

Vào trong email mà chúng ta đã setup ở bên trên

Setup Crontab

Edit kernel.php trong app/Console với nội dung như sau:

  protected function schedule(Schedule $schedule)
    {
        $schedule->command('backup:clean'); // giữ lại số lượng file mà bạn đã config
        $schedule->command('backup:run');  // backup dữ liệu
    }

Chạy lệnh:

crontab -e 

Để setup cron theo h Cho nội dung sau vào:

0 0 * * * php /home/public_html/project_name/artisan schedule:run >> /dev/null 2>&1

Ở đây tôi đặt cron này chạy vào 00h00 hằng ngày.

Login vào dropbox nó sẽ tạo ra một thư mục app chứa source và database của bạn như này:

Hi vọng rằng bài viết hữu ích với tất cả các bạn, nếu bạn có bất kỳ thắc mắc nào xin vui long để lại comment ở phía dưới bài viết.

Thank for reading.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí