Automating PostgreSQL Backups on Linux a Guide

By Chandrashekhar Fakirpure

Updated on May 09, 2024

In this article, we'll explain about automating PostgreSQL backups on Linux a guide.

To take an automatic backup of a PostgreSQL database on Linux, we can create a shell script that utilizes the pg_dump utility provided by PostgreSQL. Here's a simple example of how we can do this:

1. Create a shell script

First, we need to create a shell script and name the file backup_postgres.sh.

nano backup_postgres.sh

Add following contents in the file:

#!/bin/bash

# Define PostgreSQL database credentials
DB_USER="your_username"
DB_NAME="your_database_name"

# Define backup directory and filename
BACKUP_DIR="/path/to/backup/directory"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="$BACKUP_DIR/db_backup_$DATE.sql"

# Execute pg_dump to backup the database
pg_dump -U "$DB_USER" "$DB_NAME" > "$BACKUP_FILE"

Note:

  • Replace DB_USER and DB_NAME with your database name and user.
  • Replace BACKUP_DIR path.

2. Make the script executable

We need to make the script executable so that the crontab will run the file.

chmod +x backup_postgres.sh

3. Set up a cron job

Set up a cron job to execute the script at desired intervals. For example, to run the backup script daily, open your crontab file:

crontab -e

And add the following line to run the script at midnight every day:

0 0 * * * /path/to/backup_postgres.sh

Note: Replace /path/to/ to your file path

This will create a backup of your PostgreSQL database daily at midnight and store it in the specified backup directory with a timestamped filename.

That's it. We have successfully seen automating PostgreSQL backups on Linux a guide.