【PostgreSQL】【シェルスクリプト】PostgreSQLのバックアップスクリプト
今回は PosgreSQL のバックアップスクリプトを作成して CRON で定期バックアップを取得する手順について解説します。
基本的な PostgreSQL の操作方法に関しては以下の記事を参考にしてください。
【PostgreSQL】【CentOS7】yum コマンドでインストール&初期設定(ユーザー作成、パスワード設定、データベース作成、権限割り当て)手順
目次
PostgreSQLのバージョン
今回バックアップを取得する PostgreSQL のバージョンは以下です。
PostgreSQL:9.2.23
[root@SAKURA_VPS conf]# psql --version |
バックアップは pg_dump コマンドで取得する
データベースを運用している最中でもデータベースのバックアップを取得することが出来るコマンドです。
[root@SAKURA_VPS conf]# which pg_dump |
pg_dump コマンドのオプション
-C, --create オプション
Begin the output with a command to create the database itself and reconnect to the created database. (With a script of this form, it doesn't matter which database in the destination installation you connect to before running the script.)
If --clean is also specified, the script drops and recreates the target database before reconnecting to it.
This option is only meaningful for the plain-text format. For the archive formats, you can specify the option when you call pg_restore.
-C オプションを付けると、dump を取得する際に、dump データをリストアする時にデータベース自体を作成し、作成したデータベースに再接続するコマンドが dump データに入ります。(表現が難しいですが。。)
--cleanも指定されている場合、スクリプトは再接続する前にターゲットデータベースを削除して再作成します。
このオプションは、プレーンテキスト形式でのみ意味があります。
-E encoding, --encoding=encoding オプション
指定した文字セット符号化方式でダンプを作成します。
デフォルトではダンプはデータベースの符号化方式で作成されます。
【例】
-E UTF8
--disable-dollar-quoting オプション
このオプションは、関数本体用のドル引用符の使用を無効にし、強制的に標準 SQL の文字列構文を使用した引用符付けを行います。
-F format --format=format オプション
出力形式を選択します。 formatには以下のいずれかを取ることができます。
p, plain
-
平文のSQLスクリプトファイルを出力します(デフォルト)。
【例】
--format=plain
作成した PostgreSQL バックアップスクリプト
以下が今回作成した PostgreSQL データベース バックアップ シェルスクリプトです。
-bash-4.2$ vi postgresql_backup.sh # コマンド終了ステータスのチェック # gzip コマンドでデータを圧縮する |
CRON の設定
上記のスクリプトを CRON で毎日0時(24時)に実行します。
-bash-4.2$ crontab -l # 毎日24時に PostgreSQL データベースをバックアップする |
コメントを残す