Skip to main content

Automated PostgreSQL Backups to S3 via Bash & Cron

Database Server Infrastructure

Automated PostgreSQL Backups: A Production Bash & Cron Blueprint

Database backup failures are catastrophic when disaster strikes. Relying on manual database exports leads to data loss and unverified recovery points. Setting up an automated pipeline that dumps PostgreSQL tables, compresses the archive using gzip, and syncs the output to remote object storage guarantees data durability.

In this guide, we will build an automated shell script for PostgreSQL backups and schedule it via system cron jobs.


1. Prerequisites & AWS CLI Setup

First, ensure the AWS CLI tool and PostgreSQL client utilities are installed on your Linux host environment:

sudo apt update && sudo apt install -y postgresql-client awscli gzip

Configure credentials for an IAM user with Write permissions to your S3 bucket:

aws configure

2. Writing the Production Backup Script

Create a backup script at /usr/local/bin/pg_backup.sh:

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

Paste the following shell automation script:

#!/usr/bin/env bash
set -euo pipefail

# Configuration parameters
DB_NAME="production_db"
DB_USER="postgres"
S3_BUCKET="s3://my-company-postgres-backups"
BACKUP_DIR="/var/backups/postgresql"
DATE=$(date +%Y-%m-%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}_${DATE}.sql.gz"

# Create local destination directory if not existing
mkdir -p "${BACKUP_DIR}"

echo "==> Starting database dump for: ${DB_NAME} at ${DATE}..."

# Export database dump directly into gzip stream
pg_dump -U "${DB_USER}" -h localhost -d "${DB_NAME}" -F p | gzip -9 > "${BACKUP_FILE}"

echo "==> Backup complete. Size: $(du -h "${BACKUP_FILE}" | cut -f1)"

echo "==> Uploading backup to S3..."
aws s3 cp "${BACKUP_FILE}" "${S3_BUCKET}/$(date +%Y/%m)/${DB_NAME}_${DATE}.sql.gz"

echo "==> Purging local backups older than 7 days..."
find "${BACKUP_DIR}" -type f -name "*.sql.gz" -mtime +7 -delete

echo "==> Backup process finalized successfully!"

3. Setting Executable Permissions

Make the backup script executable and secure file access permissions so non-root users cannot read operational scripts:

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

4. Automating Execution with Cron

Open the system crontab editor for the root user to run the script every midnight at 00:00 AM:

sudo crontab -e

Add the following line at the bottom of the crontab file:

0 0 * * * /usr/local/bin/pg_backup.sh >> /var/log/pg_backup.log 2>&1

Summary

Your PostgreSQL host now executes zero-touch automated daily backups compressed with level-9 gzip, syncs structured date archives directly to S3 cloud storage, and automatically cleans up local host disk storage after 7 days.

Comments

Popular posts from this blog

Production Log Management with

Production Log Management on Linux: Mastering logrotate for High-Uptime Servers Unmanaged log growth is one of the most common causes of unexpected production outages. When application or web server logs fill up host disk partitions, database transactions fail, services crash, and systems become un-writeable. Linux provides a built-in utility called logrotate to automatically compress, rotate, and archive old log files. 1. Understanding logrotate Structure System logrotate configurations are split between two main locations: /etc/logrotate.conf — Global baseline configurations. /etc/logrotate.d/ — Service-specific configuration files (e.g., Nginx, Docker, custom apps). 2. Creating a Custom Application Log Rule Create a rule file for a custom production web service at /etc/logrotate.d/jam-app : /var/log/jam-app/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data www-data sharedscripts ...

Building High-Performance AI Infrastructure on Linux: From NVIDIA Drivers to vLLM Production Deployments

  The modern Machine Learning landscape relies entirely on Linux infrastructure. While high-level framework developments like PyTorch, Hugging Face, and LangChain dominate developer discussions, the actual engine serving low-latency inference at scale sits directly on Linux kernels, GPU acceleration drivers, and containerized serving engines. In this guide, we will step through the core architecture required to turn a raw Linux server (Ubuntu/Debian or RHEL/Rocky) into a high-throughput, OpenAI-compatible AI inference endpoint using vLLM and Docker . 1. Prerequisites & Linux Kernel Preparation Before running any Large Language Model (LLM) inference engine, your host operating system must be properly configured with NVIDIA proprietary drivers and the NVIDIA Container Toolkit to allow Docker containers direct access to host GPU acceleration. Step 1.1: Verify GPU Hardware Ensure your host system correctly detects all installed NVIDIA GPUs: Bash # Check PCI bus for recognized NVI...