Direkt zum Hauptinhalt

Daten einer einzelnen Apllikation sichern

Beschreibung:

Es gibt momente da möchte man nicht alles wiederherstellen, sondern nur eine Einzelne Applikation.
Oder man möchte eine Applikation mit Daten auf eine andere Instanz übertragen.

Vorrausetzung:

Der SQL-Server ist von außen erreichbar oder auf den gleichem Host erreichbar.
DIe Applikationen die transferiert werden haben quelle und ziel den gleichen Versionsstand.

Abblauf:

Appliaktion auf neue Instanz ausrollen.
Applikationsdaten auf neue Instanz ausrollen (Die vorhandenen aus der Datenbank werden gelöscht).

Backupprogramm erstellen:

Das Backupprogramm ist ein docker-container auf Debian 13 trixie basis

Es besteht aus einer dockerfile
einem Script
einer docker-compose datei

Das Script backup_Script.py

#!/usr/bin/python3
import os
import subprocess
from datetime import datetime

def backup_or_restore():
    # Read environment variables
    host = os.getenv("BACKUP_HOST")
    database = os.getenv("BACKUP_DATABASE")
    schema = os.getenv("BACKUP_SCHEMA")
    user = os.getenv("BACKUP_USER")
    password = os.getenv("BACKUP_PASSWORD")
    action = os.getenv("BACKUP_ACTION", "backup")
    restore_file = os.getenv("RESTORE_FILE")  # Datei für das Restore

    # Set backup file name with current date
    backup_file = f"/backup/{database}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql"

    # Set environment variable for password
    env = {"PGPASSWORD": password}

    if action == "backup":
        # Create the backup command
        command = [
            "pg_dump",
            "-h", host,
            "-U", user,
            "-d", database,
            "-n", schema,
            "-f", backup_file
        ]
        try:
            print("Erstelle Backup...")
            subprocess.run(command, env=env, check=True)
            print(f"Backup erfolgreich erstellt: {backup_file}")
        except subprocess.CalledProcessError as e:
            print(f"Fehler beim Erstellen des Backups: {e}")

    elif action == "restore":
        # Verwende die angegebene Datei oder den automatisch benannten Dateinamen
        if not restore_file:
            print("Fehler: Keine Datei für das Restore angegeben.")
            return
        
        drop_schema_command = f"DROP SCHEMA IF EXISTS {schema} CASCADE;\n"
        
        try:
            # Read the specified backup file
            with open(restore_file, 'r') as f:
                backup_content = f.read()

            restore_content = drop_schema_command + backup_content

            # Write to a temporary file
            temp_file = f"{restore_file}.temp.sql"
            with open(temp_file, 'w') as f:
                f.write(restore_content)

            # Run the restore command
            command = [
                "psql",
                "-h", host,
                "-U", user,
                "-d", database,
                "-f", temp_file
            ]
            print("Stelle Backup wieder her...")
            subprocess.run(command, env=env, check=True)
            print("Wiederherstellung erfolgreich.")

            # Delete the temporary file
            os.remove(temp_file)
            print(f"Temporäre Datei gelöscht: {temp_file}")

        except Exception as e:
            print(f"Fehler bei der Wiederherstellung: {e}")
    else:
        print("Ungültige Aktion. Verwenden Sie 'backup' oder 'restore'.")

if __name__ == "__main__":
    backup_or_restore()

Dockerfile:

# Base image: Debian 13
FROM debian:trixie

# Install Python3 and PostgreSQL client tools
RUN apt update && \
    apt install -y python3 python3-pip postgresql-client && \
    rm -rf /var/lib/apt/lists/*

# Set the work directory and backup directory
WORKDIR /backup

# Copy the Python script to /usr/bin
COPY backup_script.py /usr/bin/backup_script.py
RUN chmod +x /usr/bin/backup_script.py

# Set environment variables
ENV BACKUP_HOST ""
ENV BACKUP_DATABASE ""
ENV BACKUP_SCHEMA ""
ENV BACKUP_USER ""
ENV BACKUP_PASSWORD ""
ENV BACKUP_ACTION "backup"  # Default action is "backup", can be "restore" as well

# Run the script on container start
ENTRYPOINT ["/usr/bin/backup_script.py"]

Docker compose datei

version: '3.3'

services:    
    postgres_backup:
      build: .
      environment:
        - BACKUP_HOST=127.0.0.1 #hostname or ip
        - BACKUP_DATABASE=app #database name for rei3 let it os
        - BACKUP_SCHEMA=hacker_soft_lizenzmanager #the applikation name
        - BACKUP_USER=app #rei 3 standard user
        - BACKUP_PASSWORD=app #your password (app is standard)
        - BACKUP_ACTION=restore  # Use "backup" for backup and  "restore" for restore actions
        - RESTORE_FILE=/backup/app_20241027_195303.sql #the path to file to restore
      volumes:
        - ./backup:/backup  # Mount local backup folder
      restart: "no"  # Do not restart automatically

Starten:

Den container starten. Beim ertsen mal wird da image erstellt wenn es noch nicht besteht.

docker-compose up -d postgres_backup

Soll das Image neuerstellt werden dann

docker-compose up -d --build postgres_backup