0
0
PostgresqlHow-ToBeginner · 4 min read

How to Schedule Automatic Backup in PostgreSQL Easily

To schedule automatic backups in PostgreSQL, use the pg_dump tool combined with a system scheduler like cron on Linux or Task Scheduler on Windows. This setup runs backup commands at set times, saving your database data automatically.
📐

Syntax

The basic command to back up a PostgreSQL database is pg_dump. You specify the database name and output file. To automate, you schedule this command with a system scheduler like cron.

  • pg_dump -U [username] -F c -b -v -f [backup_file] [database_name]: Runs the backup.
  • cron: Schedules the backup command to run automatically at specified times.
bash
pg_dump -U username -F c -b -v -f /path/to/backup/file.backup database_name
💻

Example

This example shows how to schedule a daily backup at 2 AM using cron on a Linux system. It runs pg_dump to save the database to a file with the current date.

bash
# Open the cron editor
crontab -e

# Add this line to schedule daily backup at 2 AM
0 2 * * * pg_dump -U postgres -F c -b -v -f /var/backups/postgres_backup_$(date +\%Y\%m\%d).backup mydatabase

# Save and exit the editor
⚠️

Common Pitfalls

Common mistakes when scheduling PostgreSQL backups include:

  • Not setting the correct PATH or environment variables in the scheduler, causing pg_dump to fail.
  • Forgetting to provide the database password or using passwordless authentication methods like ~/.pgpass.
  • Not verifying backup success or rotating old backups, which can fill disk space.

Always test your backup command manually before scheduling.

bash
### Wrong way: cron job without full path or environment
0 2 * * * pg_dump -U postgres -F c -b -v -f /var/backups/backup.backup mydatabase

### Right way: specify full path and environment
0 2 * * * /usr/bin/pg_dump -U postgres -F c -b -v -f /var/backups/backup.backup mydatabase
📊

Quick Reference

TaskCommand / Description
Backup commandpg_dump -U username -F c -b -v -f /path/to/backup/file.backup database_name
Schedule with croncrontab -e and add: 0 2 * * * /usr/bin/pg_dump ...
Password handlingUse ~/.pgpass file for automatic authentication
Backup rotationManually or script to delete old backups
Verify backupTest restore with pg_restore

Key Takeaways

Use pg_dump with system schedulers like cron to automate PostgreSQL backups.
Always specify full paths and environment variables in scheduled jobs.
Use a .pgpass file to avoid password prompts during automated backups.
Regularly verify backups and manage old backup files to save space.
Test backup commands manually before automating them.