Backend Cookbook 4: Restore PostgreSQL Database

Yes Lee
3 min readSep 10, 2019

--

原岩攀岩館的大門門把

Database 的 Backup 在 Backend Cookbook 3: Regularly Backup Dockerized PostgreSQL Database to AWS S3 中做過了,而有了 Backup 之後,當意外發生時就有辦法做 Restore 的動作了。

由於大部分的 Infrastructure 都在實作 Backup 時都已經建立好了,所以基於其上要再來做 Restore 時就變得很輕鬆。

Folder Structure

延續 Backup 的 Folder,多加了一個 restore.sh

- docker-compose.yml
- cron
|- .env
|- Dockerfile
|- .aws
|- credentials
|- etc
|- crontab
|- scripts
|- start.sh
|- backup.sh
|- restore.sh

scripts/restore.sh

Restore 共有四個步驟:

  1. 利用 dropdb 刪除 Database
  2. 利用 createdb 新增一個空的 Database
  3. 利用 aws s3 cp 下載 AWS S3 上的 Backup Script
  4. 利用 catpsql 重建 Database
#!/bin/shfile_path=/app/db-backup/
s3_bucket=s3://yes-pangolin
file_name=db-backup-20190910000001.sql
dropdb -U user_name db_name
createdb -U user_name pangolin
aws s3 cp $s3_bucket/db-backup/$file_name $file_path
cat $file_path/$file_name | psql -U user_name -d db_name

Execution

最後透過 docker-compose execcron Container 執行 Restore。

docker-compose exec cron ./scripts/restore-db.sh

成功!

不過這種 Restore 的方式會有 Downtime 就是,如何做到沒有 Downtime 可以當作下個課題。

--

--

Yes Lee
Yes Lee

Written by Yes Lee

Frontend Engineer in Taiwan.

No responses yet