一、环境

备份工具:pg_dump、pg_restore

本地备份服务器:192.168.108.112
远程备份服务器:192.168.50.122

定时任务:crontab

服务器中pg_restore程序所在路径:

  • 本地服务器:/usr/bin/pg_restore
  • 远程服务器:/opt/postgresql-12/bin/pg_restore

二、数据备份

本地备份

1.创建备份目录

1
mkdir -p /backup/script

2.编写备份脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
vim /backup/script/backup.sh 
#!/bin/bash
nowtime=$(date +%F+%T)
export PGPASSWORD=123456
/usr/bin/pg_dump --file "/backup/pgsql-"$nowtime".backup" --host "192.168.108.112" --port "5432" --username "postgres" "revenue" --verbose --role "postgres" --format=c --blobs --encoding "UTF8"
exit;

语法:
pg_dump [选项]... [数据库名字]
参数:
-f, --file=FILENAME 输出文件或目录名
-h, --host=主机名 数据库服务器的主机名或套接字目录
-p, --port=端口号 数据库服务器的端口号
-U, --username=名字 以指定的数据库用户联接
-v, --verbose 详细模式
--role=ROLENAME 在转储前运行SET ROLE
-F, --format=c|d|t|p 输出文件格式(定制,目录,tar,明文(默认值))
-b, --blobs 在转储中包括大对象
-E, --encoding=ENCODING 转储以ENCODING形式编码的数据

3. 编写清理脚本

1
2
3
vim /backup/script/clean.sh 
#!/bin/bash
find /backup -name "pgsql*" -mtime +30 -exec rm -rf {} \

4.赋予脚本执行权限

1
2
chmod +x /backup/script/backup.sh 
chmod +x /backup/script/clean.sh

5.创建定时任务

1
2
3
crontab -e 
00 22 * * * /backup/script/backup.sh
30 22 * * * /backup/script/clean.sh

远程备份

1.安装postgresql相关工具

1
2
3
4
5
6
7
wget https://ftp.postgresql.org/pub/source/v12.20/postgresql-12.20.tar.gz 
mkdir /opt/postgresql-12
tar zxvf postgresql-12.20.tar.gz
cd postgresql-12.20
./configure --prefix=/opt/postgresql-12/
make -j 4
make install

2.创建备份目录

1
mkdir -p /backup/{pgsql,script}

3.编写远程备份脚本

1
2
3
4
5
6
vim /backup/script/backup.sh 
#!/bin/bash
nowtime=$(date +%F+%T)
export PGPASSWORD=123456
/opt/postgresql-12/bin/pg_dump --file "/backup/pgsql/pgsql-"$nowtime".backup" --host "192.168.108.112" --port "5432" --username "postgres" "revenue" --verbose --role "postgres" --format=c --blobs --encoding "UTF8"
exit;

4.编写清理脚本

1
2
3
vim /backup/script/clean.sh 
#!/bin/bash
find /backup -name "*.backup" -mtime +30 -exec rm -rf {} \;

5.创建定时任务

1
2
3
crontab -e 
00 23 * * * /backup/script/backup.sh
00 22 * * * /backup/script/clean.sh

三、数据恢复

1
2
3
4
5
6
7
8
9
10
11
12
13
14
pg_restore -h 192.168.1.10 -p 5432 -U postgres -W -d test -v test.backup 

语法:
pg_restore [connection-option] [option] filename

connection-option 参数:
-h, --host 连接地址
-p, --port 连接端口号
-U, --username 连接用户
-W, --password 强制输入密码,在某些情况下,值得键入 -W 来避免额外的连接尝试。

option 参数:
-d, --dbname 连接到数据库dbname并且直接恢复到该数据库中。
-v, --verbose 详细模式