Skip to main content

Postgres Database Backup

This guide requires Postgress installed on unRAID in a docker container and the User Scripts addon.

1. Create a new script

Create a new script in the User Scripts plugin, and call it FileFlows-DB-Backup

2. Edit the Script

Edit the script by running

nano /boot/config/plugins/user.scripts/scripts/FileFlows-DB-Backup/script 

3. Code

Paste the following code replacing container with the name of your Postgres Docker container and backup_dir with your backup location

#!/bin/bash

# Define the backup directory (ensure proper quoting)
backup_dir="/mnt/user/backups/postgres"

# Define the database name (ensure proper quoting)
dbName="FileFlows"

# Define the docker container name for the Postgres server (ensure proper quoting)
container="postgresql15"

# Perform the backup
docker exec "$container" pg_dump -U postgres -F t "$dbName" | gzip > "$backup_dir/$dbName-$(date +%Y-%m-%d).tar.gz"

# Check if backup was successful
if [ $? -ne 0 ]; then
echo "Backup failed!"
exit 1
fi

# Remove old backup files if there are more than 30
backup_count=$(ls -1Q "$backup_dir" | grep "^$dbName-" | wc -l)
if [ "$backup_count" -gt 30 ]; then
# Determine the number of files to delete
files_to_delete=$((backup_count - 30))
# Delete the oldest files
ls -1trQ "$backup_dir" | grep "^$dbName-" | head -n "$files_to_delete" | xargs -I {} rm "$backup_dir"/{}
fi

4. Test the Script

Run the script from the User Scripts and check its output, confirm a new backup was saved to the backup path.