Dumping a PostgreSQL database and automating the process

There are many reasons why you'd need to have your data in a dump, and one of those is to back it up.

Source(s):
https://djangocentral.com/backup-and-restore-data-in-postgresql/
https://unix.stackexchange.com/questions/96380/how-to-append-date-to-backup-file
https://www.linuxtechi.com/schedule-automate-tasks-linux-cron-jobs/
https://unix.stackexchange.com/questions/42715/how-can-i-make-cron-run-a-job-right-now-for-testing-debugging-without-changing   
Configuration   
- PostgreSQL 13.7
- Debian 11
  

The command is as follows:  

pg_dump -U db_user -F t db_name > /path/to/your/file/dump_name.tar

  
1. U specifies the user  
2. F specifies the file format, *.tar in this case  
3. ">" pipes the output to a file of your choosing   
  

Cherry on top  

  
It would be nice to see the date of the backup straight away, so let's try to automate that.  

pg_dump -U db_user -F t db_name > /path/to/your/file/dump_name_$(date +%F_%R).tar

  
That command produces a nice date string, and it's really easy to see what the backup is and when it was created.   

#sample output

mainsite_2022-06-07_13:58.tar

  
The only thing left now was to automate it, and I chose Crontab as the tool to do it. I decided to run it as my specific user, since that would not mess up the user rights of my backups.      

micro myscript.sh
crontab -u username -e

  

#myscript.sh

echo "hello"

  
Just to test it out.  

  

#!/bin/bash <- Tells that we'll be using this to execute our task

* * * * * /mylocation/myscript.sh

  
The logs proved that I had succeeded in my automation.   
  

kallet@fenix2:~$ sudo tail /var/log/syslog |grep backup
Jun  7 14:45:01 fenix2 CRON[87646]: (username) CMD (/home/username/publicwsgi/ktcom/backup.sh)
Jun  7 14:46:01 fenix2 CRON[87669]: (username) CMD (/home/username/publicwsgi/ktcom/backup.sh)

  
So, now it was about making the command the right one and the backup interval something more sensible, like once every day.     
  

crontab -u username -e

  

#!/bin/bash

0 1 * * * /home/username/publicwsgi/ktcom/backup.sh

  

#myscript.sh

#!/bin/bash

pg_dump -U db_user -F t db_name > /mylocation/mainsite_$(date +%F_%R).tar

  
That will now take a database backup every day at 01.00.

All articles


Comments

No published comments yet.


Add a Comment

Your comment is held for review before it appears publicly.

Your email is never published or shared.

Up to 2,000 characters.

Tick the box, then click Submit right away (Google expires the check after about two minutes).