Backing up PostgreSQL databases using cron jobs
Automated backups are essential for protecting your data. On ruachost.com, you can schedule PostgreSQL backups using cron jobs, ensuring your databases are regularly saved without manual intervention.
Why Use Cron Jobs for Backups?
Section titled “Why Use Cron Jobs for Backups?”- Automates routine backups.
- Reduces risk of data loss.
- Ensures recovery points are always available.
- Saves time compared to manual exports.
Steps to Set Up Automated Backups
Section titled “Steps to Set Up Automated Backups”Step 1: Configure .pgpass File
Section titled “Step 1: Configure .pgpass File”Cron jobs run without user interaction, so you must store database credentials securely in a .pgpass file.
-
Log in via SSH.
-
Create a file named
.pgpassin your home directory:Terminal window nano ~/.pgpass -
Add the following line (replace placeholders with actual values):
hostname:port:database:username:passwordExample:
localhost:5432:mydb:dbuser:dbpassword -
Set file permissions:
Terminal window chmod 600 ~/.pgpass
Step 2: Create Backup Command
Section titled “Step 2: Create Backup Command”Use pg_dump to export the database.
/usr/bin/pg_dump --no-password -U dbuser dbname > /home/username/backups/mydb_backup.pgsql- Replace
dbuser,dbname, andusernamewith your actual values. - Ensure the backup path exists (
/home/username/backups/).
Step 3: Schedule Cron Job
Section titled “Step 3: Schedule Cron Job”-
Open the crontab editor:
Terminal window crontab -e -
Add a line to schedule the backup. Example: run daily at 2 AM:
0 2 * * * /usr/bin/pg_dump --no-password -U dbuser dbname > /home/username/backups/mydb_backup.pgsql -
Save and exit.
Example Cron Expressions
Section titled “Example Cron Expressions”-
Daily at 2 AM
Section titled “Daily at 2 AM”0 2 * * * ... -
Every Sunday at midnight
Section titled “Every Sunday at midnight”0 0 * * 0 ... -
Every 6 hours
Section titled “Every 6 hours”
0 */6 * * * ...