Backup

自動備份 PostgreSQL 數據庫的最佳方法是什麼?

  • October 6, 2020

我發現每週都必須備份數據庫很乏味。而且我還認為每周備份應該變成每日備份。如果我必須這樣做,我不想手動進行。每天自動備份 PostgreSQL 數據庫的最佳方法是什麼?

就像您對任何其他可以自動化的重複性任務所做的一樣 - 您編寫一個腳本來進行備份,然後設置一個 cron 作業來執行它。

例如,如下所示的腳本:

(注意:它必須以 postgres 使用者或任何其他具有相同權限的使用者身份執行)

#! /bin/bash

# backup-postgresql.sh
# by Craig Sanders <cas@taz.net.au>
# This script is public domain.  feel free to use or modify
# as you like.

DUMPALL='/usr/bin/pg_dumpall'
PGDUMP='/usr/bin/pg_dump'
PSQL='/usr/bin/psql'

# directory to save backups in, must be rwx by postgres user
BASE_DIR='/var/backups/postgres'
YMD=$(date "+%Y-%m-%d")
DIR="$BASE_DIR/$YMD"
mkdir -p "$DIR"
cd "$DIR"

# get list of databases in system , exclude the tempate dbs
DBS=( $($PSQL --list --tuples-only |
         awk '!/template[01]/ && $1 != "|" {print $1}') )

# first dump entire postgres database, including pg_shadow etc.
$DUMPALL --column-inserts | gzip -9 > "$DIR/db.out.gz"

# next dump globals (roles and tablespaces) only
$DUMPALL --globals-only | gzip -9 > "$DIR/globals.gz"

# now loop through each individual database and backup the
# schema and data separately
for database in "${DBS[@]}" ; do
   SCHEMA="$DIR/$database.schema.gz"
   DATA="$DIR/$database.data.gz"
   INSERTS="$DIR/$database.inserts.gz"

   # export data from postgres databases to plain text:

   # dump schema
   $PGDUMP --create --clean --schema-only "$database" |
       gzip -9 > "$SCHEMA"

   # dump data
   $PGDUMP --disable-triggers --data-only "$database" |
       gzip -9 > "$DATA"

   # dump data as column inserts for a last resort backup
   $PGDUMP --disable-triggers --data-only --column-inserts \
       "$database" | gzip -9 > "$INSERTS"

done

# delete backup files older than 30 days
echo deleting old backup files:
find "$BASE_DIR/" -mindepth 1 -type d -mtime +30 -print0 |
   xargs -0r rm -rfv

編輯:

pg_dumpall -D開關(第 27 行)已棄用,現在替換為--column-inserts

https://wiki.postgresql.org/wiki/Deprecated_Features

引用自:https://serverfault.com/questions/59838