0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Django】VPSでDBのdumpファイル作成とローカルへのバックアップ

Posted at

バックアップを作成

VPSにSSH接続し仮想環境を有効化、manage.pyがあるディレクトリに移動する。

$ cd dir_name
$ source env/bin/activate
$ cd project_name

dumpdata実行

アプリケーション名を指定しない場合、インストールされているすべてのアプリケーションがダンプされる。以下のコマンドはjsonで作成しているが、xml、jsonl、yamlでの作成も可能。

terminal
USERNAME@xxx.xxx.xxx.xxx:~$ python manage.py dumpdata > dump_last.json

しかし、このまま実行するとエラーが発生することが良くある。

私の場合permissioncontent_typeesを除外すると解決する事が多い。

terminal
USERNAME@xxx.xxx.xxx.xxx:~$ python manage.py dumpdata --exclude auth.permission --exclude contenttypes > dump_last.json

この辺はデータベースの状態によって変わると思うので、エラーの内容をみて対応する。

作成先

dumpdataで作成したファイルは、カレントディレクトリに作成されるので、lsを実行するとdump_last.jsonが表示されるはずです。

VPS
USERNAME@xxx.xxx.xxx.xxx:~/dir_name/project_name $ ls
dump_last.json manage.py その他色々

ローカルにダウンロード

SSH接続を終了しターミナルで実行する。

この時、VPSで操作する必要があるのでは?と思うかもしれないが、「ローカルにVPSにあるファイルをダウンロードする」のでをローカルで実行する。

-i オプションを使用することで、scpコマンドがリモートホストに接続する際に、指定したpemファイルを使用して認証を行います。

terminal
$ scp -i /Users/name/.ssh/hoge.pem name@xxx.xxx.xxx.xxx:~/dir_name/project_name/dump_last.json ~/Desktop/

SCP + -i + pemファイルのパス + ユーザー名とIP:dumpファイルのパス + ローカルの保存先のパス

という形です。

ローカルからアップロード

ダウンロードコマンドのパスを逆にするだけ。

terminal
$ scp -i /Users/name/.ssh/hoge.pem ~/Desktop/ name@xxx.xxx.xxx.xxx:~/dir_name/project_name/dump_last.json

インポート

当たり前ですが、dumpファイルに対応しているデータベースがないとインポートできないので、プロジェクトやアプリを作り直した場合は、migrateしてから実行する。

VPS
$ python manage.py loaddata dump_last.json
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?