Implement Redis backup automation with compression and encryption

Intermediate 25 min Apr 16, 2026 734 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up automated Redis backups with compression and GPG encryption for production environments. Create systemd timers for scheduled backups and implement secure remote storage for Redis data protection.

Prerequisites

  • Redis server installed and running
  • Root or sudo access
  • Basic familiarity with Redis and systemd

What this solves

Redis backup automation ensures your critical data is protected with regular snapshots, compression to save storage space, and encryption for security compliance. This tutorial sets up automated Redis backups using RDB dumps, gzip compression, and GPG encryption with systemd timers for scheduling.

Install Redis backup dependencies

Update system packages

Start by updating your package manager to ensure you get the latest versions of backup tools.

sudo apt update && sudo apt upgrade -y
sudo dnf update -y

Install backup dependencies

Install the required tools for Redis backup automation, including compression utilities and GPG for encryption.

sudo apt install -y gzip tar gnupg2 rsync cron
sudo dnf install -y gzip tar gnupg2 rsync cronie

Create backup directories

Set up dedicated directories for Redis backups with proper ownership and permissions for security.

sudo mkdir -p /opt/redis-backup/{scripts,data,logs}
sudo mkdir -p /var/backups/redis
sudo chown -R redis:redis /opt/redis-backup
sudo chown -R redis:redis /var/backups/redis
sudo chmod 750 /opt/redis-backup
sudo chmod 750 /var/backups/redis

Create automated backup scripts with compression

Generate GPG encryption key

Create a dedicated GPG key pair for Redis backup encryption. This ensures backup files are encrypted at rest.

sudo -u redis gpg --gen-key

Follow the prompts to create the key. Use a strong passphrase and save it securely. For automated backups, you can also create a key without a passphrase:

sudo -u redis gpg --batch --gen-key <

Create the main backup script

Create a comprehensive backup script that handles Redis data dumping, compression, and encryption.

#!/bin/bash

# Redis Backup Script with Compression and Encryption
# Configuration
REDIS_CLI="/usr/bin/redis-cli"
REDIS_HOST="127.0.0.1"
REDIS_PORT="6379"
REDIS_AUTH=""
BACKUP_DIR="/var/backups/redis"
LOG_FILE="/opt/redis-backup/logs/backup.log"
RETENTION_DAYS=30
GPG_RECIPIENT="redis-backup@example.com"

# Create timestamp
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_NAME="redis_backup_${TIMESTAMP}"

# Logging function
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Check if Redis is running
check_redis() {
    if ! $REDIS_CLI -h $REDIS_HOST -p $REDIS_PORT ping > /dev/null 2>&1; then
        log_message "ERROR: Redis server is not responding"
        exit 1
    fi
}

# Create Redis dump
create_dump() {
    log_message "Starting Redis backup: $BACKUP_NAME"
    
    # Force Redis to save current dataset
    if [ -n "$REDIS_AUTH" ]; then
        $REDIS_CLI -h $REDIS_HOST -p $REDIS_PORT -a $REDIS_AUTH BGSAVE
    else
        $REDIS_CLI -h $REDIS_HOST -p $REDIS_PORT BGSAVE
    fi
    
    # Wait for background save to complete
    while [ $($REDIS_CLI -h $REDIS_HOST -p $REDIS_PORT LASTSAVE) -eq $($REDIS_CLI -h $REDIS_HOST -p $REDIS_PORT LASTSAVE) ]; do
        sleep 1
    done
    
    log_message "Redis BGSAVE completed successfully"
}

# Copy and compress dump file
backup_and_compress() {
    REDIS_DATA_DIR="/var/lib/redis"
    DUMP_FILE="$REDIS_DATA_DIR/dump.rdb"
    
    if [ ! -f "$DUMP_FILE" ]; then
        log_message "ERROR: Redis dump file not found at $DUMP_FILE"
        exit 1
    fi
    
    # Copy dump file to backup directory
    cp "$DUMP_FILE" "$BACKUP_DIR/${BACKUP_NAME}.rdb"
    
    # Compress the backup
    gzip "$BACKUP_DIR/${BACKUP_NAME}.rdb"
    
    log_message "Backup compressed: ${BACKUP_NAME}.rdb.gz"
}

# Encrypt backup file
encrypt_backup() {
    cd "$BACKUP_DIR"
    
    # Encrypt the compressed backup
    gpg --trust-model always --encrypt -r "$GPG_RECIPIENT" "${BACKUP_NAME}.rdb.gz"
    
    if [ $? -eq 0 ]; then
        # Remove unencrypted file
        rm "${BACKUP_NAME}.rdb.gz"
        log_message "Backup encrypted successfully: ${BACKUP_NAME}.rdb.gz.gpg"
    else
        log_message "ERROR: Failed to encrypt backup file"
        exit 1
    fi
}

# Clean old backups
cleanup_old_backups() {
    find "$BACKUP_DIR" -name "redis_backup_*.gpg" -mtime +$RETENTION_DAYS -delete
    log_message "Cleaned up backups older than $RETENTION_DAYS days"
}

# Verify backup integrity
verify_backup() {
    BACKUP_FILE="$BACKUP_DIR/${BACKUP_NAME}.rdb.gz.gpg"
    
    if [ -f "$BACKUP_FILE" ]; then
        BACKUP_SIZE=$(stat -c%s "$BACKUP_FILE")
        if [ $BACKUP_SIZE -gt 0 ]; then
            log_message "Backup verification successful: $BACKUP_SIZE bytes"
        else
            log_message "ERROR: Backup file is empty"
            exit 1
        fi
    else
        log_message "ERROR: Backup file not found"
        exit 1
    fi
}

# Main execution
main() {
    log_message "Starting automated Redis backup process"
    
    check_redis
    create_dump
    backup_and_compress
    encrypt_backup
    verify_backup
    cleanup_old_backups
    
    log_message "Redis backup completed successfully: ${BACKUP_NAME}.rdb.gz.gpg"
}

# Run main function
main

Create backup restore script

Create a companion script to restore Redis backups when needed.

#!/bin/bash

# Redis Restore Script
# Usage: ./redis-restore.sh backup_file.rdb.gz.gpg

if [ $# -ne 1 ]; then
    echo "Usage: $0 

Make scripts executable

Set proper permissions on the backup scripts to ensure they can be executed by the redis user.

sudo chmod +x /opt/redis-backup/scripts/*.sh
sudo chown redis:redis /opt/redis-backup/scripts/*.sh

Configure systemd timers for scheduled backups

Create systemd service unit

Create a systemd service that runs the Redis backup script with proper user context and error handling.

[Unit]
Description=Redis Backup Service
After=redis.service
Requires=redis.service

[Service]
Type=oneshot
User=redis
Group=redis
ExecStart=/opt/redis-backup/scripts/redis-backup.sh
StandardOutput=append:/opt/redis-backup/logs/service.log
StandardError=append:/opt/redis-backup/logs/service.log

Create systemd timer unit

Set up a timer to run Redis backups automatically at scheduled intervals.

[Unit]
Description=Redis Backup Timer
Requires=redis-backup.service

[Timer]
OnCalendar=daily
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target

Enable and start the timer

Reload systemd configuration and enable the backup timer to start automatically.

sudo systemctl daemon-reload
sudo systemctl enable redis-backup.timer
sudo systemctl start redis-backup.timer

Create log rotation configuration

Set up log rotation to prevent backup logs from consuming too much disk space.

/opt/redis-backup/logs/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 644 redis redis
    postrotate
        /bin/systemctl reload rsyslog > /dev/null 2>&1 || true
    endscript
}

Implement GPG encryption for backup files

Export GPG public key for backup

Export the GPG public key to enable backup restoration on other systems if needed.

sudo -u redis gpg --armor --export redis-backup@example.com > /opt/redis-backup/redis-backup-public.key

Test backup encryption

Run a test backup to ensure the encryption process works correctly.

sudo -u redis /opt/redis-backup/scripts/redis-backup.sh

Verify encrypted backup files

Check that backup files are properly encrypted and can be decrypted when needed.

ls -la /var/backups/redis/
sudo -u redis gpg --list-packets /var/backups/redis/redis_backup_*.gpg | head -10

Verify your setup

Test the complete backup and restore process to ensure everything works correctly.

# Check timer status
sudo systemctl status redis-backup.timer
sudo systemctl list-timers redis-backup.timer

# Check Redis connectivity
redis-cli ping

# View backup logs
sudo tail -f /opt/redis-backup/logs/backup.log

# List backup files
ls -la /var/backups/redis/

# Test manual backup
sudo systemctl start redis-backup.service
sudo systemctl status redis-backup.service

For more advanced Redis backup strategies, you can also refer to our guide on implementing Redis backup automation with RDB and AOF persistence.

Common issues

SymptomCauseFix
GPG encryption failsMissing or incorrect GPG keyVerify key exists: sudo -u redis gpg --list-keys
Permission denied errorsIncorrect file ownershipFix ownership: sudo chown -R redis:redis /opt/redis-backup
Timer not runningTimer not enabledEnable timer: sudo systemctl enable redis-backup.timer
Backup script failsRedis not respondingCheck Redis status: sudo systemctl status redis-server
Large backup filesCompression not workingVerify gzip is installed and working: gzip --version
Old backups not cleanedRetention cleanup failedCheck find command syntax in cleanup function
Note: Always test backup restoration in a non-production environment before relying on automated backups in production. Store GPG private keys securely and consider using a backup key management solution for enterprise environments.

If you're running Redis in a cluster setup, check our tutorial on setting up Redis cluster with multiple master nodes for cluster-specific backup considerations.

Next steps

Automated install script

Run this to automate the entire setup

Don't want to manage this yourself?

We handle infrastructure for businesses that depend on uptime. Fully managed, with one fixed contact who knows your setup.

You get one fixed contact who knows your setup

Rotterdam 01:26 · reachable in a message, no ticket form