Scheduled Backups for PostgreSQL Databases

PostgreSQL is an open-source object-relational database management system.

This document shows how to create scheduled backups of a PostgreSQL database on Opalstack.

The examples use mydb as the database name, mydbuser as the database user name, and mydbpassword as the database user password - be sure to replace those values with the names of your own database, user, and password.

1

Log in to a SSH session on your Opalstack server.

2

Create the files and directories used by your scheduled MariaDB backups:

mkdir -m 700 -p ~/.local/bin
mkdir -m 700 -p ~/.local/etc/psql_backups
mkdir -m 700 -p ~/backups/psql
touch ~/.pgpass
chmod 600 ~/.pgpass
touch ~/.local/bin/backup_mydb
chmod 700 ~/.local/bin/backup_mydb
3

Edit the database credentials file named ~/.pgpass and add the following line:

localhost:5432:mydb:mydbuser:mydbpassword
4

Edit the script ~/.local/bin/backup_mydb and add the following lines that will run your backup:

#!/bin/bash

export DBNAME=mydb
export DBUSER=mydbuser

/bin/pg_dump -b -Fp -U $DBUSER $DBNAME \
    > $HOME/backups/psql/$DBNAME-$(date +%Y%m%d%H%M).sql \
    2>> $HOME/backups/psql/$DBNAME.log
5

Run crontab -e and create a crontab entry to schedule the backup. The following example will schedule the backup to run daily at 3:30 AM UTC (server time):

30 3 * * * $HOME/.local/bin/backup_mydb

Please see the following pages for general help with cron jobs:

Once the above steps are complete, your backup will run at the schedule time to create a backup of your PostgreSQL database in ~/backups/psql on the server.