Postgres DB backup script
To export a postgres database We use the pg_dump command:
pg_dump -U postgres -v DATABASE -f FILENAME.sql
And to import it back we use psql:
psql -U postgres -W -d "FILENAME.sql" < FILENAME.sql
Now that we know these commands We can easily create a bash that will backup 2 postgres databases from the server and upload them to the backup Windows server while keeping 7 backups locally.
#!/bin/bash
ntpdate pool.ntp.org
cd /root/
now="$(date +'%d%m%Y%H%M')"
export PGPASSWORD="strong"
pg_dump -U postgres -h localhost DB1_NAME -f /root/tmp_dbs/backup_DB1_$now.sql
pg_dump -U postgres -h localhost DB2_NAME -f /root/tmp_dbs/backup_DB2_$now.sql
tar cvfz /root/backup_dbs/backup_$now.tar.gz /root/tmp_dbs/*
rm /root/tmp_dbs/*
mount -t nfs 172.20.20.6:/mnt/backup /mnt/
rsync -ruv /root/backup_dbs/ /mnt/172.20.20.12/
find /root/backup_dbs/* -mtime +7 -delete
umount /mnt/
exit 0
Explained:
#!/bin/bash
ntpdate pool.ntp.org
#store backups in /root
cd /root/
#add timestamp to each backup
now="$(date +'%d%m%Y%H%M')"
#postgres db password for our databases
export PGPASSWORD="strong"
#1st database
pg_dump -U postgres -h localhost DB1_NAME -f /root/tmp_dbs/backup_DB1_$now.sql
#2nd database
pg_dump -U postgres -h localhost DB2_NAME -f /root/tmp_dbs/backup_DB2_$now.sql
#compress and remove originals
tar cvfz /root/backup_dbs/backup_$now.tar.gz /root/tmp_dbs/*
rm /root/tmp_dbs/*
#mount Windows server
mount -t nfs 172.20.20.6:/mnt/backup /mnt/
#copy files
rsync -ruv /root/backup_dbs/ /mnt/172.20.20.12/
#remove files older than 7 days
find /root/backup_dbs/* -mtime +7 -delete
umount /mnt/
exit 0
Leave Postgres DB backup script to:
Read more #wordpress posts
Best Posts From PCx3
We have not curated any of pcx3's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From PCx3
- 🚨 Critical Vulnerability in Sitepad cPanel plugin ≤ 1.7.0
- Fatal Error Unable to create lock file: Bad file descriptor (9)
- Remove custom reseller branding when transferring cPanel accounts
- No request delivery notification has been received from LSAPI application, possible dead lock.
- aaPanel security log is vulnerable to stored XSS
- logrotate usage with examples
- Exclude ai1wm-backup folder from Softaculous backups
- CWP Successful login keeps redirecting back to the login page
- UID MOVE: IMAP session state is inconsistent, please relogin.
- Softaculuos Prestashop installation error: Unable to generate new_cookie_key, hence can not install Prestashop 1.7