postgresql数据库备份

使用docker启动postgresql数据库,默认用户:postgres,通过-e POSTGRES_PASSWORD=123456指定postgres用户密码。

[root@localhost ~]# docker run --name postgres_asd -e POSTGRES_PASSWORD=123456 -p 5433:5432 -d postgres:11.7-alpine
e93f36df0c60e27c869771b12becc42a276e9b041eb60536e06e7ad635309ab6

进入容器,连接数据库,通过\l\list列出所有数据库,创建test_db数据库。

[root@localhost ~]# docker exec -ti postgres_asd /bin/bash
bash-5.0#
bash-5.0# psql "host=127.0.0.1 port=5432 user=postgres password=123456"
psql (11.7)
Type "help" for help.

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(3 rows)
postgres=#
postgres=# \list
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(3 rows)
postgres=#
postgres=# CREATE DATABASE test_db;
CREATE DATABASE
postgres=#
postgres=# exit
bash-5.0#

进入容器,创建备份目录,使用pg_dump "host=127.0.0.1 port=5432 user=postgres password=123456 dbname=test_db" > /home/backup/postgre-$(date +%Y%m%d).dump进行数据库的备份。

[root@localhost ~]# docker exec -ti postgres_asd /bin/bash
bash-5.0# mkdir /home/backup/
bash-5.0#
bash-5.0# pg_dump "host=127.0.0.1 port=5432 user=postgres password=123456 dbname=test_db" > /home/backup/postgre-$(date +%Y%m%d).dump
bash-5.0#
bash-5.0# cd /home/backup/
bash-5.0# ls
postgre-20211207.dump

清空test_db,通过备份文件来进行恢复

bash-5.0# pg_dump "host=127.0.0.1 port=5432 user=postgres password=123456 dbname=test_db" < /home/backup/postgre-20211207.dump

编写shell脚本,实现数据库的备份同时仅保留三天的备份文件:

#!/bin/bash -ev
time pg_dump "host=127.0.0.1 port=5432 user=postgres password=123456 dbname=test_db" > /home/backup/postgre-$(date +%Y%m%d).dump
#保留3天数据
time find /home/backup/ -type f -name "*.dump" -mtime +3 -print0 | xargs -0 -I {} rm -vf {}

find -print0和xargs -0原理及用法:参考https://www.jianshu.com/p/6370c721269e

https://www.postgresql.org/docs/current/backup-dump.html

你可能感兴趣的:(postgresql数据库备份)