LoginSignup
20
25

More than 3 years have passed since last update.

【Laravel】LaravelのソースもDBも簡単にバックアップが取れる「spatie/laravel-backup」

Last updated at Posted at 2019-05-28

LaravelのソースもDBもバックアップを取る

毎日、DBのバックアップが取りたかったのでLaravel用のライブラリで何かないかなーとを探していたら
spatie/laravel-backupというのを見つけたので使ってみました。

インストール

composerからインストール

最新版のv6をインストールするには以下のコマンドを実行

$ composer require spatie/laravel-backup

ただ、最新版のv6は、PHP7.2以上かつLaravel5.8以上を要求してくるので、もしLTSのLaravel5.5系のサービスに入れる場合はv5を指定するようにします。

v5をインストールする場合は以下のように指定

$ composer require "spatie/laravel-backup:5.*"

ここでは基本的にv5を入れた状態で書いていきます

config/backup.php生成

以下のコマンドを実行

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

すると、configディレクトリ以下にbackup.phpが生成される

バックアップコマンドを実行する

まるっとソースごと全部バックアップ

$ php artisan backup:run

※この状態で特に通知先の設定をしていないとエラーがでます。

通知機能無効オプション

$ php artisan backup:run --disable-notifications

DBのみバックアップ

$ php artisan backup:run --only-db

DBのみバックアップ(通知機能無効)

$ php artisan backup:run --only-db --disable-notifications

バックアップ時の通知先(メール)設定

メールの設定をする場合はmailtoに通知先のメールアドレスを設定すれば毎回バックアップコマンドを実行した際にメールが飛ぶようになります。
(※メール送信設定している前提)

config/backup.php
        /*
         * 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@example.com',
        ],

通知先に複数のメールアドレスを設定する場合は以下のように書いて、メールアドレスを.envに書くようにすれば後々の追加も楽かなと

config/backup.php
        'mail' => [
            'to' => array_map('trim', explode(',', env('NOTIFICATIONS_MAIL_ADDRESS'))),
        ],

.envファイルに,区切りで記述

NOTIFICATIONS_MAIL_ADDRESS=hoge@example.com,test@example.com

古いバックアップのクリーンアップ

$ php artisan backup:clean

詳細設定

以下の部分を適切に設定する

config/backup.php
    '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' => 31,

            /*
             * The number of days for which daily backups must be kept.
             * (日次バックアップを保持する必要がある日数)
             */
            'keepDailyBackupsForDays' => 31,

            /*
             * The number of weeks for which one weekly backup must be kept.
             * (週1回のバックアップを保持する必要がある週数)
             */
            'keepWeeklyBackupsForWeeks' => 8,

            /*
             * The number of months for which one monthly backup must be kept.
             * (毎月1回のバックアップを保存する月数)
             */
            'keepMonthlyBackupsForMonths' => 4,

            /*
             * The number of years for which one yearly backup must be kept.
             * (年1回のバックアップを保持する必要がある年数)
             */
            'keepYearlyBackupsForYears' => 2,

            /*
             * After cleaning up the backups remove the oldest backup until
             * this amount of megabytes has been reached.
             * (バックアップをクリーンアップした後、このメガバイト数に達しています(?))
             */
            'deleteOldestBackupsWhenUsingMoreMegabytesThan' => 5000,
        ],
    ],

クリーンアップのルールとしては以下の通りです。

This package provides an opinionated method to determine which old backups should be deleted. We call this the DefaultStrategy. This is how it works:

Rule #1: it will never delete the latest backup regardless of its size or age
Rule #2: it will keep all backups for the number of days specified in keepAllBackupsForDays
Rule #3: it will only keep daily backups for the number of days specified in keepDailyBackupsForDays for all backups older than those covered by rule #2
Rule #4: it will only keep weekly backups for the number of months specified in keepMonthlyBackupsForMonths for all backups older than those covered by rule #3
Rule #5: it'll only keep yearly backups for the number of years specified in keepYearlyBackupsForYears for all backups older than those covered by rule #4
Rule #6: it will start deleting old backups until the volume of storage used is lower than the amount specified in deleteOldestBackupsWhenUsingMoreMegabytesThan.

Of course the numbers used in the default configuration can be adjusted to suit your own needs.

以下みらい翻訳

このパッケージには、削除する必要のある古いバックアップを判断するための独自の方法が用意されています。これをDefaultStrategyと呼びます。その仕組みは次のとおりです。

ルール1:サイズや経過時間にかかわらず、最新のバックアップを削除しない
ルール#2:keepAllBackupsForDaysで指定された日数の間、すべてのバックアップを保持します。
ルール#3:ルール#2の対象よりも古いすべてのバックアップについて、keepDailyBackupsForDaysで指定された日数の日次バックアップのみが保持されます。
ルール#4:ルール#3の対象よりも古いすべてのバックアップについて、keepMonthlyBackupsForMonthsで指定された月数の間だけ週単位のバックアップを保持する
ルール#5:ルール#4の対象よりも古いすべてのバックアップについて、keepYearlyBackupsForYearsで指定された期間だけ毎年バックアップを保持します。
ルール6:使用されるストレージのボリュームがd e l e O l d e stBackupsWhenUsingMoreMegabytesThanで指定された量より少なくなるまで、古いバックアップの削除を開始します。

もちろん、デフォルト設定で使用されている数値は、必要に応じて調整できます。

(正直この設定に関してはよくわかっていないので詳しい方教えてください。。)

定期的にバックアップを実行する(cronの設定)

app\Console\Kernel.php以下のscheduleメソッドへコマンドを実行するように記述し、サーバー側でcronの設定を行えば定期的にバックアップを実行するようにできます

app\Console\Kernel.php
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('backup:clean');
        $schedule->command('backup:run --only-db');
    }

以下cron設定(実行間隔はサーバーによって設定可否が異なるので省略)

php /your-project-path/artisan schedule:run >> /dev/null 2>&1

以下等参考にしてください。

※レンタルサーバーによってはシェルスクリプトしか実行できなかったりするので注意してください。

参考URL

20
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
25