Skip to content

Instantly share code, notes, and snippets.

@ride90
Last active March 15, 2020 17:49
Show Gist options
  • Save ride90/b86ca6650139d168752df4359a433450 to your computer and use it in GitHub Desktop.
Save ride90/b86ca6650139d168752df4359a433450 to your computer and use it in GitHub Desktop.
Dump postgresql DB every day and keep dump files not older than 30 days

create a sh script for a cron

db_backup.sh

#!/bin/bash

# make a backup
pg_dump -Fc --no-owner --dbname=postgresql://user:pswd@host:port/db_name > /folder/with/backups/db_`date +\%Y-\%m-\%d_\%T`.dump;
# delete files with *.dump older than 30 days
find . -name "*.dump" -type f -mtime 30 -exec rm -f {} \;

edit crontab config

crontab -e

paste job configuration

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

# db backup + clean old files at 03:00  in the morning
0 3 * * * /folder/with/backups/backup_db.sh

restore with pg_restore

pg_restore -c --no-owner --dbname=postgresql://user:password@host:port/db_name a/folder/with/backups/backup_file_name.dump
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment