Netbird/scripts/backup-netbird.sh

105 lines
2.5 KiB
Bash
Raw Normal View History

#!/bin/bash
2025-11-27 16:23:27 +00:00
# Netbird Docker Compose Backup Script
# This script stops the services, creates a timestamped backup, and restarts services
# Configuration
COMPOSE_DIR="/home/Dejan/Docker/Netbird-compose"
BACKUP_DIR="${COMPOSE_DIR}/backup"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_NAME="netbird-backup-${TIMESTAMP}.tar.gz"
BACKUP_PATH="${BACKUP_DIR}/${BACKUP_NAME}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Function to print colored messages
print_msg() {
echo -e "${GREEN}[INFO]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
# Check if running as root
if [ "$EUID" -ne 0 ]; then
print_error "Please run as root"
exit 1
fi
# Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]; then
print_msg "Creating backup directory: $BACKUP_DIR"
mkdir -p "$BACKUP_DIR"
fi
# Change to compose directory
cd "$COMPOSE_DIR" || {
print_error "Failed to change to directory: $COMPOSE_DIR"
exit 1
}
print_msg "Starting backup process..."
print_msg "Timestamp: $TIMESTAMP"
# Stop docker compose services
print_msg "Stopping Docker Compose services..."
docker compose stop
if [ $? -eq 0 ]; then
print_msg "Services stopped successfully"
else
print_error "Failed to stop services"
exit 1
fi
# Create backup (excluding the backup directory itself and git directory)
print_msg "Creating backup archive: $BACKUP_NAME"
tar -czf "$BACKUP_PATH" \
--exclude='./backup' \
--exclude='./.git' \
--exclude='*.tar.gz' \
-C "$COMPOSE_DIR" .
if [ $? -eq 0 ]; then
print_msg "Backup created successfully: $BACKUP_PATH"
BACKUP_SIZE=$(du -h "$BACKUP_PATH" | cut -f1)
print_msg "Backup size: $BACKUP_SIZE"
else
print_error "Failed to create backup"
docker-compose up -d
exit 1
fi
# Restart docker compose services
print_msg "Starting Docker Compose services..."
docker compose up -d
2025-11-27 16:23:27 +00:00
if [ $? -eq 0 ]; then
print_msg "Services started successfully"
else
print_error "Failed to start services"
exit 1
fi
# Optional: Keep only last N backups (uncomment to enable)
KEEP_BACKUPS=5
print_msg "Cleaning old backups, keeping last $KEEP_BACKUPS..."
cd "$BACKUP_DIR"
ls -t netbird-backup-*.tar.gz | tail -n +$((KEEP_BACKUPS + 1)) | xargs -r rm
print_msg "Old backups cleaned"
2025-11-27 16:23:27 +00:00
print_msg "Backup process completed successfully!"
print_msg "Backup location: $BACKUP_PATH"
# List recent backups
print_msg "Recent backups:"
ls -lht "$BACKUP_DIR"/netbird-backup-*.tar.gz | head -n 5
2025-11-27 16:23:27 +00:00
exit 0