Friday, 15 September 2017

PostgreSQL: Scheduler to take db backup every two hours

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

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 file executable (chmod +x

4. Now it's the time to set scheduler:

crontab -e

It will open scheduler file. Add following line at the end of file

1 */2 * * * /home/ubuntu/

To know how these parameters work please visit

That's it.

Now backup will be taken every two hours and backup file will be stored in ~/backup folder.

Thanks!!!! Enjoy Programming!! :)

No comments:

Post a Comment

Thanks for your valuable comments.

Nginx: Cannot allocate memory