Site icon PlusMagi's Blog By Pitt Phunsanit

Docker: Samba Import

เป็น shell script ที่จะ import samba container จาก folder data_backup

  1. สร้างไฟล์
    touch data_restore.sh
  2. ใส่เนื้อหา
    #!/bin/bash
    
    # Configuration with Defaults
    VOLUME_NAME="${1:-ad-samba-data}"
    BACKUP_DIR="${2:-./data_backup}"
    
    echo "=========================================="
    echo " Samba AD DC Restore Utility"
    echo "=========================================="
    echo "Volume Name: $VOLUME_NAME"
    echo "Backup Dir : $BACKUP_DIR"
    echo "------------------------------------------"
    
    # List available backups
    echo "Available Backups:"
    ls -1 "$BACKUP_DIR"/*.tar.gz 2>/dev/null
    if [ $? -ne 0 ]; then
    	echo "❌ No backup files found in $BACKUP_DIR"
    	exit 1
    fi
    echo "------------------------------------------"
    
    # Ask user for backup file to restore
    read -p "Enter backup filename to restore (e.g., ad_samba_backup_2026...tar.gz): " BACKUP_FILENAME
    
    FULL_BACKUP_PATH="${BACKUP_DIR}/${BACKUP_FILENAME}"
    
    if [ ! -f "$FULL_BACKUP_PATH" ]; then
    	echo "❌ Error: Backup file not found: $FULL_BACKUP_PATH"
    	exit 1
    fi
    
    echo "⚠️  WARNING: This will OVERWRITE existing data in volume '$VOLUME_NAME'!"
    read -p "Are you sure you want to continue? (y/N): " CONFIRM
    if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    	echo "Restore cancelled."
    	exit 0
    fi
    
    echo "Restoring from: $FULL_BACKUP_PATH"
    
    # 1. Stop the container first
    echo "Stopping container..."
    docker compose stop
    
    if [ $? -ne 0 ]; then
    	echo "❌ Failed to stop container. Restore aborted."
    	exit 1
    fi
    
    # 2. Restore using a temporary alpine container
    # - Mount the volume to /target_volume
    # - Mount the backup directory to /backup_dir
    # - Wipe the volume
    # - Extract the backup file
    echo "Wiping volume and extracting backup..."
    docker run --rm \
      -v "$VOLUME_NAME":/target_volume \
      -v "$(pwd)/$BACKUP_DIR":/backup_dir \
      alpine \
      sh -c "rm -rf /target_volume/* && tar xzf /backup_dir/$BACKUP_FILENAME -C /target_volume"
    
    RESTORE_STATUS=$?
    
    # 3. Start the container again
    echo "Starting container..."
    docker compose start
    
    # 4. Check Result
    if [ $RESTORE_STATUS -eq 0 ]; then
    	echo "✅ Restore successful."
    else
    	echo "❌ Restore failed!"
    	exit 1
    fi
    
  3. ให้สิทธิ์
    chmod +x data_restore.sh

restore

สามารถทำได้ง่าย ๆ โดยคำสั่ง

./data_restore.sh

จะนำไฟล์ Backup ล่าสุด ( หรือที่ระบุ ) กลับเข้าไปใน Volume ( ข้อมูลเดิมจะถูกลบ )

options

ตัวอย่างการนำสคริปต์ไปรันใช้งานจริง


อ่านเพิ่มเติม

Exit mobile version