PostgreSQL備份與恢復


前言

PostgreSQL自帶的備份工具有pg_basebackup、pg_dump、pg_dumpall。

區別:

  • pg_basebackup是文件系統級別的備份,可用於連續歸檔方案。
  • pg_dump、pg_dumpall都是是邏輯備份,前者支持多種備份格式,后者只支持sql文本。

1 pg_start_backup

        pg_start_backup() 和 pg_stop_backup()是postgreSQL提供的一種備份方式,由於無法並行備份,現在已經逐漸被pg_basebackup工具(postgresql9.1之后)所替代。

        pg_start_backup() 和 pg_stop_backup()的使用是不需要開啟歸檔的(強烈建議開啟),那么在進行備份的時候,應該進行歸檔的一部分日志就會無法保存直接被覆蓋掉,如果再想恢復到“歸檔日志之后”的時間段數據也就會發生丟失。


pg_start_backup()
 1、強制發生一次checkpoint點。 將未寫到磁盤上的臟數據全部刷到磁盤上去。這樣從這之后產生的日志就是記錄整個數據塊。可以“確保”恢復的正確性。
 2、置寫日志標志為:XLogCtl->Insert.forcePageWrites = true,這樣wal日志將會記錄整個數據塊。避免了在進行備份時候(讀操作——舊數據)持續向數據庫寫入數據(寫操作——新數據)造成的前后數據不一致
 3、pg_start_backup()開啟期間(不執行pg_stop_backup()),wal日志仍然會進行循環使用。從我們使用者的角度來看也許數據庫應該是持續的將數據塊變化記錄到wal中,備份不停止,wal日志也不應該被覆蓋,但事實上並不是如此,也許是postgreSQL為了不至於太復雜和為了避免撐爆xlog日志,pg_start_backup()開啟期間wal仍會進行覆蓋循環使用。

 

pg_stop_backup()的作用就是結束此次備份狀態,以便進行下次備份(非並發性備份),一直不執行pg_stop_backup()也並不會撐爆xlog目錄,但是是無法執行下次備份的。

2 pg_basebackup

2.1 介紹

        pg_basebackup用於獲得一個正在運行的PostgreSQL數據庫的基礎備份。獲得這些備份不會影響連接到該數據庫的其他客戶端,並且可以被用於時間點恢復。

        pg_basebackup建立數據庫集簇文件的一份二進制副本,同時保證系統進入和退出備份模式。備份總是從整個數據庫集簇獲得,不可能備份單個數據庫或數據庫對象。關於個體數據庫備份,必須使用一個像pg_dump的工具。

        備份通過一個常規PostgreSQL連接制作,並且使用復制協議。該連接必須由一個超級用戶或者一個具有REPLICATION權限的用戶建立,並且pg_hba.conf必須顯式地允許該復制連接。該服務器還必須被配置,使max_wal_senders設置得足夠大以留出至少一個會話用於備份。

        在同一時間可以有多個pg_basebackup運行,但是從性能的角度來說最好只做一個備份並且復制結果。

        pg_basebackup不僅能從主控機也能從后備機創建一個基礎備份。要從后備機獲得一個備份,設置后備機讓它能接受復制連接(也就是,設置max_wal_senders和hot_standby,並且配置基於主機的認證)。你將也需要在主控機上啟用full_page_writes。

注意在來自后備機的在線備份中有一些限制:

  • 不會在被備份的數據庫集簇中創建備份歷史文件。
  • 不保證備份所需的所有 WAL 文件在備份結束時被歸檔。如果你計划將該備份用於一次歸檔恢復並且想要確保所有所需文件在那個時刻都可用,你需要通過使用-x將它們包括在備份中。
  • 如果在在線備份期間后備機被提升為主控機,備份會失敗。
  • 備份所需的所有 WAL 記錄必須包含足夠的全頁寫,這要求你在主控機上啟用full_page_writes並且不使用一個類似pg_compresslog的工具以archive_command從 WAL 文件中移除全頁寫。

2.2 參數介紹

pg_basebackup幫助手冊

[root@guizhou_hp-pop-10-150-57-13 ~]# pg_basebackup --help
pg_basebackup takes a base backup of a running PostgreSQL server.

Usage:
  pg_basebackup [OPTION]...

Options controlling the output:
  -D, --pgdata=DIRECTORY receive base backup into directory
  -F, --format=p|t       output format (plain (default), tar)
  -r, --max-rate=RATE    maximum transfer rate to transfer data directory
                         (in kB/s, or use suffix "k" or "M")
  -R, --write-recovery-conf
                         write recovery.conf after backup
  -S, --slot=SLOTNAME    replication slot to use
  -T, --tablespace-mapping=OLDDIR=NEWDIR
                         relocate tablespace in OLDDIR to NEWDIR
  -x, --xlog             include required WAL files in backup (fetch mode)
  -X, --xlog-method=fetch|stream
                         include required WAL files with specified method
      --xlogdir=XLOGDIR  location for the transaction log directory
  -z, --gzip             compress tar output
  -Z, --compress=0-9     compress tar output with given compression level

General options:
  -c, --checkpoint=fast|spread
                         set fast or spread checkpointing
  -l, --label=LABEL      set backup label
  -P, --progress         show progress information
  -v, --verbose          output verbose messages
  -V, --version          output version information, then exit
  -?, --help             show this help, then exit

Connection options:
  -d, --dbname=CONNSTR   connection string
  -h, --host=HOSTNAME    database server host or socket directory
  -p, --port=PORT        database server port number
  -s, --status-interval=INTERVAL
                         time between status packets sent to server (in seconds)
  -U, --username=NAME    connect as specified database user
  -w, --no-password      never prompt for password
  -W, --password         force password prompt (should happen automatically)

Report bugs to <pgsql-bugs@postgresql.org>.

 

參數注釋:

類型 參數 說明
控制輸出的選項 -D, --pgdata=DIRECTORY 接收基礎備份的路徑
-F, --format=p|t 指定備份格式(p=無格式,t=tar格式)
-r, --max-rate=RATE 從該服務器傳輸數據的最大傳輸率(默認KB/s,可指定"K"或"M")
-R, --write-recovery-conf 備份完成后寫入recovery.conf文件
-S, --slot=SLOTNAME 指定復制槽
-T, --tablespace-mapping=OLDDIR=NEWDIR 將OLDDIR中的表空間重新定位到NEWDIR
-x, --xlog 在備份中包含所需的WAL文件(fetch模式)
-X, --xlog-method=fetch|stream 使用指定的方法包含所需的WAL文件 (fetch,stream模式)
--xlogdir=XLOGDIR 指定事務日志目錄的路徑
-z, --gzip tar壓縮輸出
-Z, --compress=0-9 指定壓縮級別
一般參數 -c, --checkpoint=fast|spread 設置檢查點的方式(fast或spread)
-l, --label=LABEL 設置備份標簽
-P, --progress 顯示進度信息
-v, --verbose 輸出詳細信息
-V, --version 查看版本信息
-?, --help 幫助手冊
連接參數 -d, --dbname=CONNSTR pg_basebackup並不連接到集簇中的任何特定數據庫,連接字符串中的數據庫名將被忽略。
-h, --host=HOSTNAME 指定數據庫主機或socket
-p, --port=PORT 指定數據庫端口
-s, --status-interval=INTERVAL 指定發送狀態給服務器的時間間隔秒()
-U, --username=NAME 指定連接用戶名
-w, --no-password 不提示輸入密碼
-W, --password 強制提示輸入密碼(默認)

2.3 備份案例

創建本地基礎備份,並存儲到/home/postgres/2021-12-06

[postgres]# pg_basebackup -U repl -D /home/postgres/2021-12-06 -P
Password: 
809339/809339 kB (100%), 1/1 tablespace
NOTICE:  pg_stop_backup complete, all required WAL segments have been archived

[postgres]# ls /home/postgres/2021-12-06/
arch_log      backup_label.old  global   pg_commit_ts  pg_hba.conf    pg_log      pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  postgresql.auto.conf  recovery.done
backup_label  base              pg_clog  pg_dynshmem   pg_ident.conf  pg_logical  pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_xlog     postgresql.conf       tablespace_map.old

 

創建本地基礎備份並打包壓縮,並存儲到/home/postgres/2021-12-06

[postgres]# pg_basebackup -U repl -Ft -z -P -D /home/postgres/2021-12-06/
940414/940414 kB (100%), 1/1 tablespace
NOTICE:  pg_stop_backup complete, all required WAL segments have been archived

[postgres]# ls /home/postgres/2021-12-06/
base.tar.gz

 

 用於復制流的基礎備份

[postgres]# pg_basebackup -h 10.150.57.13 -U repl -X stream -P -D $PGDATA
Password: 
1202567/1202567 kB (100%), 1/1 tablespace

 2.4 時間點恢復(PITR)

案例1:使用連續歸檔進行恢復

開啟歸檔模式

[postgres]# vi $PGDATA/portgresql.conf
wal_level=hot_standby
archive_mode = on
archive_command = 'cp %p /usr/local/pgsql/data/arch_log/%f && find /usr/local/pgsql/data/arch_log -type f -mtime +3 | xargs rm -fr'

 

基礎備份

[postgres]# pg_basebackup -U repl -Ft -z -P -D /home/postgres/2021-12-06/
940414/940414 kB (100%), 1/1 tablespace
NOTICE:  pg_stop_backup complete, all required WAL segments have been archived

[postgres]# ls /home/postgres/2021-12-06/
base.tar.gz

 

 模擬故障,誤刪數據庫數據文件,導致數據庫異常(如果WAL日志丟失,恢復會丟失部分事務)。

 

拷貝基礎備份到$PGDATA目錄下,然后配置recovery.conf

[root]# vi $PGDATA/recovery.conf
restore_command = 'cp /usr/local/pgsql/data/arch_log/%f %p'

 

啟動PostgreSQL

[postgres]# pg_ctl start

案例2:基於時間線恢復

與上面的例子區別在於recovery.conf

[root]# vi $PGDATA/recovery.conf
restore_command = 'cp /usr/local/pgsql/data/arch_log/%f %p'
#recovery_target_time = '2021-12-06 20:24:45.871979 CST'
#recovery_target_time = '2021-12-06 20:24:45.871979+08'
recovery_target_time = '2021-12-06 20:24:45'
recovery_target_inclusive = true
recovery_target_timeline = 'latest'

控制恢復停止的位置:

  • recovery_target_name:指pg_create_restore_point(text)創建的還原點,如果有重名的還原點,那么在recovery過程中第一個遇到的還原點即停止。
  • recovery_target_time:指XLOG中記錄的recordXtime(xl_xact_commit_compact->xact_time),配合recovery_target_inclusive使用,
  • recovery_target_xid:指XLogRecord->xl_xid,可以配合recovery_target_inclusive使用,但是recovery_target_inclusive只影響日志的輸出,並不影響恢復進程截至點的選擇,截至都截止於這個xid的xlog位置。也就是說無論如何都包含了這個事務的xlog信息的recovery。xid的信息體現在結束時,而不是分配xid時。所以恢復到xid=100提交|回滾點,可能xid=102已經先提交了。那么包含xid=102的xlog信息會被recovery。
  • recovery_target_inclusive:
    • 如果在同一個時間點有多個事務回滾或提交,那么recovery_target_inclusive=false則恢復到這個時間點第一個回滾或提交的事務(含),recovery_target_inclusive=true則恢復到這個時間點最后一個回滾或提交的事務(含)。
    • 如果時間點上剛好只有1個事務回滾或提交,那么recovery_target_inclusive=true和false一樣,恢復將處理到這個事務包含的xlog信息(含)。
    • 如果時間點沒有匹配的事務提交或回滾信息,那么recovery_target_inclusive=true和false一樣,恢復將處理到這個時間后的下一個事務回滾或提交的xlog信息(含)。

3 pg_dump

3.1 介紹

pg_dump是邏輯備份工具,支持多種輸出格式。

3.2 幫助手冊

查看pg_dump幫助手冊

[postgres]# pg_dump --help
pg_dump dumps a database as a text file or to other formats.

Usage:
  pg_dump [OPTION]... [DBNAME]

General options:
  -f, --file=FILENAME          output file or directory name
  -F, --format=c|d|t|p         output file format (custom, directory, tar,
                               plain text (default))
  -j, --jobs=NUM               use this many parallel jobs to dump
  -v, --verbose                verbose mode
  -V, --version                output version information, then exit
  -Z, --compress=0-9           compression level for compressed formats
  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock
  -?, --help                   show this help, then exit

Options controlling the output content:
  -a, --data-only              dump only the data, not the schema
  -b, --blobs                  include large objects in dump
  -c, --clean                  clean (drop) database objects before recreating
  -C, --create                 include commands to create database in dump
  -E, --encoding=ENCODING      dump the data in encoding ENCODING
  -n, --schema=SCHEMA          dump the named schema(s) only
  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)
  -o, --oids                   include OIDs in dump
  -O, --no-owner               skip restoration of object ownership in
                               plain-text format
  -s, --schema-only            dump only the schema, no data
  -S, --superuser=NAME         superuser user name to use in plain-text format
  -t, --table=TABLE            dump the named table(s) only
  -T, --exclude-table=TABLE    do NOT dump the named table(s)
  -x, --no-privileges          do not dump privileges (grant/revoke)
  --binary-upgrade             for use by upgrade utilities only
  --column-inserts             dump data as INSERT commands with column names
  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting
  --disable-triggers           disable triggers during data-only restore
  --enable-row-security        enable row security (dump only content user has
                               access to)
  --exclude-table-data=TABLE   do NOT dump data for the named table(s)
  --if-exists                  use IF EXISTS when dropping objects
  --inserts                    dump data as INSERT commands, rather than COPY
  --no-security-labels         do not dump security label assignments
  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs
  --no-tablespaces             do not dump tablespace assignments
  --no-unlogged-table-data     do not dump unlogged table data
  --quote-all-identifiers      quote all identifiers, even if not key words
  --section=SECTION            dump named section (pre-data, data, or post-data)
  --serializable-deferrable    wait until the dump can run without anomalies
  --snapshot=SNAPSHOT          use given snapshot for the dump
  --strict-names               require table and/or schema include patterns to
                               match at least one entity each
  --use-set-session-authorization
                               use SET SESSION AUTHORIZATION commands instead of
                               ALTER OWNER commands to set ownership

Connection options:
  -d, --dbname=DBNAME      database to dump
  -h, --host=HOSTNAME      database server host or socket directory
  -p, --port=PORT          database server port number
  -U, --username=NAME      connect as specified database user
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
  --role=ROLENAME          do SET ROLE before dump

If no database name is supplied, then the PGDATABASE environment
variable value is used.

Report bugs to <pgsql-bugs@postgresql.org>.

 

參數解釋:

類型 參數 說明
一般選項 -f, --file=FILENAME 指定輸出文件名稱
-F, --format=c|d|t|p 指定輸出文件格式(custom, directory, tar,plain text (default))
-j, --jobs=NUM 指定多個job並行備份
-v, --verbose 輸出備份詳細信息
-V, --version 輸出版本信息
-Z, --compress=0-9 指定壓縮格式的壓縮等級
--lock-wait-timeout=TIMEOUT 指定鎖超時的時間
控制輸出文件的選項 -a, --data-only 只導出數據
-b, --blobs 在dump文件中包含大對象
-c, --clean 重建數據庫之前刪除數據庫
-C, --create 在dump文件中包含創建數據庫的命令
-E, --encoding=ENCODING 轉儲編碼為encoding的數據
-n, --schema=SCHEMA 導出此模式的數據庫
-N, --exclude-schema=SCHEMA 不導出此模式的數據
-o, --oids 在dump文件包含OID信息
-O, --no-owner skip restoration of object ownership in plain-text format
-s, --schema-only 只導出模式,不包含數據
-S, --superuser=NAME 超級用戶使用明文格式的用戶名
-t, --table=TABLE 指定導出的表名
-T, --exclude-table=TABLE 指定不導出的表名
-x, --no-privileges 不導出權限(grant/revoke)
--binary-upgrade 僅供升級工具使用
--column-inserts 將數據轉儲為帶有列名的INSERT命令  
--disable-dollar-quoting 禁用美元引用,使用SQL標准引用
--disable-triggers 在數據恢復期間禁用觸發器
--enable-row-security 啟用行安全性(僅轉儲用戶可以訪問的內容)  
--exclude-table-data=TABLE 不轉儲指定表的數據
--if-exists 如果對象存在則刪除
--inserts 將數據轉儲為INSERT命令,而不是COPY命令 
--no-security-labels 不轉儲安全標簽分配
--no-synchronized-snapshots 在並行作業中不使用同步快照 
--no-tablespaces 不備份表空間
--no-unlogged-table-data 不轉儲不記錄日志的表數據
--quote-all-identifiers 引用所有標識符,即使不是關鍵字
--section=SECTION 轉儲指定的部分(前數據、數據或后數據)  
--serializable-deferrable 等待直到轉儲可以正常運行
--snapshot=SNAPSHOT 為轉儲使用給定的快照
--strict-names 要求表和/或模式包含模式,以便每個模式至少匹配一個實體  
--use-set-session-authorization 使用SET SESSION AUTHORIZATION命令而不是ALTER OWNER命令來設置所有權  
連接參數 -d, --dbname=DBNAME 備份的數據庫名
-h, --host=HOSTNAME 數據庫的主機名或socket路徑
-p, --port=PORT 數據庫服務端口
-U, --username=NAME 連接數據庫指定的用戶
-w, --no-password 不提示輸入密碼
-W, --password 提示輸入密碼(默認會提示)
--role=ROLENAME dump指定ROLE

3.3 備份恢復

備份postgres庫

[postgres]# pg_dump -h 127.0.0.1 -p 5432 -U postgres -f postgres.sql --column-inserts

 

備份postgres庫並tar打包

[postgres]# pg_dump -h 127.0.0.1 -p 5432 -U postgres -f postgres.sql.tar -Ft

 

只備份postgres庫對象數據

[postgres]# pg_dump -U postgres -d postgres -f postgres.sql -Ft --data-only --column-inserts

 

只備份postgres庫對象結構

[postgres]# pg_dump -U postgres -d postgres -f postgres.sql -Ft --schema-only

 

導入SQL文件

[postgres]# psql -f postgre.sql postgres postgres

3.4 pg_restore恢復

備份

pg_dump -C -Fc postgres > postgres.db

恢復

[postgres]# pg_restore -l postgres.db > postgres.ini
[postgres]# pg_restore -L postgres.ini -d postgres postgres.db

 

4 pg_dumpall

4.1 介紹

pg_dumpall是邏輯備份工具,只支持導出SQL命令。

4.2 幫助手冊

查看pg_dumpall幫助手冊

[postgres]# pg_dumpall --help
pg_dumpall extracts a PostgreSQL database cluster into an SQL script file.

Usage:
  pg_dumpall [OPTION]...

General options:
  -f, --file=FILENAME          output file name
  -V, --version                output version information, then exit
  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock
  -?, --help                   show this help, then exit

Options controlling the output content:
  -a, --data-only              dump only the data, not the schema
  -c, --clean                  clean (drop) databases before recreating
  -g, --globals-only           dump only global objects, no databases
  -o, --oids                   include OIDs in dump
  -O, --no-owner               skip restoration of object ownership
  -r, --roles-only             dump only roles, no databases or tablespaces
  -s, --schema-only            dump only the schema, no data
  -S, --superuser=NAME         superuser user name to use in the dump
  -t, --tablespaces-only       dump only tablespaces, no databases or roles
  -x, --no-privileges          do not dump privileges (grant/revoke)
  --binary-upgrade             for use by upgrade utilities only
  --column-inserts             dump data as INSERT commands with column names
  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting
  --disable-triggers           disable triggers during data-only restore
  --if-exists                  use IF EXISTS when dropping objects
  --inserts                    dump data as INSERT commands, rather than COPY
  --no-security-labels         do not dump security label assignments
  --no-tablespaces             do not dump tablespace assignments
  --no-unlogged-table-data     do not dump unlogged table data
  --quote-all-identifiers      quote all identifiers, even if not key words
  --use-set-session-authorization
                               use SET SESSION AUTHORIZATION commands instead of
                               ALTER OWNER commands to set ownership

Connection options:
  -d, --dbname=CONNSTR     connect using connection string
  -h, --host=HOSTNAME      database server host or socket directory
  -l, --database=DBNAME    alternative default database
  -p, --port=PORT          database server port number
  -U, --username=NAME      connect as specified database user
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
  --role=ROLENAME          do SET ROLE before dump

If -f/--file is not used, then the SQL script will be written to the standard
output.

Report bugs to <pgsql-bugs@postgresql.org>.

 

參數解釋:

類型 參數 說明
一般參數 -f, --file=FILENAME 指定文件名稱
--lock-wait-timeout=TIMEOUT 指定等待表鎖N秒后失敗
控制輸出參數 -a, --data-only 只備份數據
-c, --clean 重建之前刪除數據庫
-g, --globals-only 僅備份全局對象,不導出數據庫
-o, --oids 在轉儲文件中包含OID
-O, --no-owner 不轉儲對象的權限信息
-r, --roles-only 僅僅轉儲role,不轉儲數據庫和表空間
-s, --schema-only 只轉儲結構,不轉儲數據
-S, --superuser=NAME 轉儲使用的超級用戶
-t, --tablespaces-only 只轉儲表空間,不包含database和role
-x, --no-privileges 不轉儲權限(grant/revoke)
--binary-upgrade 僅供升級工具使用
--column-inserts 將數據轉儲為帶有列名的INSERT命令
--disable-dollar-quoting 禁用美元引用,使用SQL標准引用
--disable-triggers 在數據恢復期間禁用觸發器
--if-exists 當刪除對象時使用IF EXISTS
--inserts 將數據轉儲為INSERT命令,而不是COPY命令
--no-security-labels 不轉儲安全標簽分配
--no-tablespaces 不轉儲表空間分配
--no-unlogged-table-data 不轉儲沒記錄日志的數據
--quote-all-identifiers 引用所有標識符,即使不是關鍵字
--use-set-session-authorization 使用SET SESSION AUTHORIZATION命令而不是ALTER OWNER命令來設置所有權  
連接選項 -d, --dbname=DBNAME 備份的數據庫名
-h, --host=HOSTNAME 數據庫的主機名或socket路徑
-p, --port=PORT 數據庫服務端口
-U, --username=NAME 連接數據庫指定的用戶
-w, --no-password 不提示輸入密碼
-W, --password 提示輸入密碼(默認會提示)
--role=ROLENAME dump指定ROLE
  -l, --database=DBNAME 選擇默認數據庫

4.3 備份恢復

備份postgres庫,轉儲數據為帶列名的INSERT命令

[postgres]# pg_dumpall -d postgres -U postgres -f postgres.sql --column-inserts

 

備份postges庫,轉儲數據為INSERT命令

[postgres]# pg_dumpall -d postgres -U postgres -f postgres.sql --inserts

 

導入數據

[postgres]#psql -f postgres.sql

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM