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?
-
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
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:Bash nano ~/.pgpass -
Add the following line (replace placeholders with actual values):
hostname:port:database:username:passwordExample:
localhost:5432:mydb:dbuser:dbpassword -
Set file permissions:
Bash chmod 600 ~/.pgpass
Step 2: Create Backup Command
Use pg_dump to export the database.
Bash
/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
-
Open the crontab editor:
Bash 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
-
Daily at 2 AM:
0 2 * * * ... -
Every Sunday at midnight:
0 0 * * 0 ... -
Every 6 hours:
0 */6 * * * ...
Important Notes
|