Hi, Today we are going to write a scheduler to take PostgreSQL db dump every two hours in ubuntu OS.
1. Create a folder called backup in your home directory where we are going to store all the dump files.
2. Because it's cron script so can provide password at runtime, we are going to store required details in ~/.pgpass file in following format
don't forget to change it's permission to 0600 (chmod 0600 ~/.pgpass)
Note: You can change localhost with Server IP if you have
3. Create a file to write script for db backup. Let's create it in home directory itself and call it db_backup.sh
Add following command to the file.
pg_dump -d mydb -h localhost -p 5432 -U user1 -w | gzip > /home/ubuntu/backup/$(date +%Y-%m-%d-%H:%m:%s).psql.gz
It will save the dump file with date and time as name. e.g 2017-09-16-07:09:1505546517.psql.gz
Don't forget to make db_backup.sh file executable (chmod +x db_backup.sh)
4. Now it's the time to set scheduler:
It will open scheduler file. Add following line at the end of file
1 */2 * * * /home/ubuntu/db_backup.sh
To know how these parameters work please visit https://crontab.guru/every-2-hours
Now backup will be taken every two hours and backup file will be stored in ~/backup folder.
Thanks!!!! Enjoy Programming!! :)