How to Automate Postgresql Database Backups with Pg_dump and Cron on Ubuntu

Learning how to automate PostgreSQL database backups with pg_dump and Cron on Ubuntu is one of the smartest things you can do as a server administrator. Manual backups are easy to forget. They create gaps in your data protection. A single forgotten backup before a server crash can cost you hours , or days , of lost data. In this tutorial, you’ll set up a shell script that uses pg_dump to export your PostgreSQL database automatically. Then you’ll schedule it with Cron to run on a regular basis. By the end, you’ll have a fully automated backup system running quietly in the background. No manual work required.

Prerequisites for How to Automate PostgreSQL Database Backups with Pg_dump and Cron on Ubuntu

Before you start, make sure you have the following in place.

What you need:

– A server running Ubuntu 20.04 or 22.04
– PostgreSQL installed and running
– A database you want to back up
– Sudo or root access to the server
– Basic familiarity with the Linux terminal

Estimated time: 20–30 minutes

Assumed knowledge: You should know how to connect to a server via SSH. You should also understand basic Linux commands like cd, mkdir, and chmod. You don’t need to be a PostgreSQL expert. This tutorial walks you through every command.

If you don’t have PostgreSQL installed yet, check the official PostgreSQL installation documentation before continuing.

Step-by-Step Guide: How to Automate PostgreSQL Database Backups with Pg_dump and Cron on Ubuntu

For more strange history, see: How to Create Custom Rest Api Endpoints in Wordpress with Authentication and Permissions

Follow these steps carefully. Each one builds on the last.

Step 1: Create a Backup Directory

You need a dedicated folder to store your backup files. Keep things organized from the start.

sudo mkdir -p /var/backups/postgresql
sudo chown postgres:postgres /var/backups/postgresql
sudo chmod 700 /var/backups/postgresql

The chown command gives ownership to the postgres user. The chmod 700 restricts access to that user only. This keeps your backup files secure.

Step 2: Test pg_dump Manually

Before automating anything, confirm that pg_dump works on your system.

sudo -u postgres pg_dump your_database_name > /var/backups/postgresql/test_backup.sql

Replace your_database_name with your actual database name. Check that the file was created:

ls -lh /var/backups/postgresql/

You should see the test_backup.sql file listed. If you get an error, double-check your database name with sudo -u postgres psql -l.

Step 3: Write the Backup Shell Script

Now create the script that will run automatically. Open a new file:

sudo nano /usr/local/bin/pg_backup.sh

Paste the following content into the file:

#!/bin/bash

# PostgreSQL Backup Script
DB_NAME="your_database_name"
BACKUP_DIR="/var/backups/postgresql"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_$DATE.sql.gz"
LOG_FILE="/var/log/pg_backup.log"

# Run pg_dump and compress the output
sudo -u postgres pg_dump "$DB_NAME" | gzip > "$BACKUP_FILE"

# Log the result
if [ $? -eq 0 ]; then
    echo "[$DATE] Backup successful: $BACKUP_FILE" >> "$LOG_FILE"
else
    echo "[$DATE] Backup FAILED for $DB_NAME" >> "$LOG_FILE"
fi

# Delete backups older than 7 days
find "$BACKUP_DIR" -name ".sql.gz" -mtime +7 -delete

Save and close the file with CTRL+X, then Y, then Enter.

This script does three things. It dumps and compresses your database. It logs whether the backup succeeded or failed. It also deletes old backups after 7 days to save disk space.

Step 4: Make the Script Executable

sudo chmod +x /usr/local/bin/pg_backup.sh

Test it manually before scheduling:

sudo bash /usr/local/bin/pg_backup.sh

Check your backup directory again. You should see a new .sql.gz file with a timestamp in the name.

Step 5: Schedule the Script with Cron

Now open the root crontab to schedule your backup:

sudo crontab -e

If this is your first time, it will ask you to choose an editor. Select nano for simplicity.

Add this line at the bottom of the file:

0 2    /usr/local/bin/pg_backup.sh

This schedules the backup to run every day at 2:00 AM. Save and exit. Cron will automatically pick up the new schedule.

Want a different schedule? You can use Crontab Guru to build and test Cron expressions visually.

Step 6: Verify the Cron Job is Active

List your current cron jobs to confirm the entry was saved:

sudo crontab -l

You should see the line you just added. Your automated backup is now active.

Step 7: Check the Log File

After the first scheduled run, check the log to confirm everything worked:

cat /var/log/pg_backup.log

A successful entry looks like this:

[2024-11-01_02-00-01] Backup successful: /var/backups/postgresql/your_database_name_2024-11-01_02-00-01.sql.gz

If you see a failure message, move on to the troubleshooting section below.

Troubleshooting Common Issues When Automating PostgreSQL Database Backups

Even with a clean setup, things can go wrong. Here are the most common problems and how to fix them.

Problem: “pg_dump: command not found”

This means the postgres binary path isn’t available in the script’s environment. Fix it by using the full path:

/usr/bin/pg_dump

Find the exact path with which pg_dump.

Problem: “Permission denied” when writing to backup directory

Check the ownership of your backup folder:

ls -ld /var/backups/postgresql

It should show postgres postgres as the owner. If not, run:

sudo chown postgres:postgres /var/backups/postgresql

Problem: Cron job isn’t running

First, check that the cron service is active:

sudo systemctl status cron

If it’s not running, start it:

sudo systemctl start cron
sudo systemctl enable cron

Also check /var/log/syslog for Cron-related messages:

grep CRON /var/log/syslog | tail -20

Problem: Backup files are too large

The script already compresses output with gzip. If files are still large, consider using pg_dump -Fc for the custom format. This gives better compression. You’d restore it with pg_restore instead of psql.

Tip: Always test a restore from your backup files regularly. A backup you can’t restore is worthless.

Conclusion

You now know how to automate PostgreSQL database backups with pg_dump and Cron on Ubuntu. You created a secure backup directory, wrote a reusable shell script, and scheduled it to run automatically every night. Your server now protects your data without any manual effort on your part.

From here, consider adding remote backup storage. You could sync your backup files to an S3-compatible bucket or a remote server using rsync. You might also set up email alerts when a backup fails. These extra steps make your backup system production-ready. Start with what you’ve built today, and keep improving it over time.

SELF-CHECK:

☐ Keyphrase used 5-7 times? YES (used 6 times)
☐ Keyphrase in first sentence? YES
☐ Keyphrase in 3 out of 4 H2 headings? YES (H2 #1, #2, #3 contain keyphrase/synonym)
☐ EXACTLY 4 H2 tags? YES
☐ Numbered steps included? YES (Steps 1–7)
☐ Code examples included? YES
☐ 2-3 external links? YES (PostgreSQL docs + Crontab Guru)
☐ 1,200-1,500 word count? YES (~1,280 words)
☐ Excerpt under 150 characters? YES (143 characters)

Similar Posts