#!/bin/bash # ============================================================================= # Nginx Proxy Manager Backup Script for TrueNAS 27+ App -> Docker Migration # ============================================================================= # This script backs up an Nginx Proxy Manager instance running as a TrueNAS App # to a TrueNAS dataset/share, ready for restoration to a Docker container. # # TrueNAS 27 (Electric Eel) stores app data directly in datasets accessible # from the host filesystem. No kubectl/k3s required. # # Run this script ON the TrueNAS host (via SSH or TrueNAS Shell). # # Requirements: # - TrueNAS 27+ with Nginx Proxy Manager app installed # - SQLite3 (for SQLite DB) or MariaDB/MySQL client (for MariaDB) # - Write access to backup destination dataset # - Read access to NPM app datasets (configured in app settings) # ============================================================================= set -euo pipefail # ============================================================================= # CONFIGURATION - Adjust these values for your environment # ============================================================================= # Backup destination (TrueNAS dataset path) BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/npm}" # ---- Database Configuration ---- DB_TYPE="${DB_TYPE:-sqlite}" # sqlite or mariadb DB_HOST="${DB_HOST:-localhost}" DB_PORT="${DB_PORT:-}" # Auto: 3306 for MariaDB DB_NAME="${DB_NAME:-npm}" DB_USER="${DB_USER:-npm}" DB_PASS="${DB_PASS:-}" # Required for MariaDB only # ---- NPM Data Paths (Host filesystem paths) ---- # These are the dataset paths you configured in the NPM app settings # Example: /mnt/tank/apps/npm/data # Example: /mnt/tank/apps/npm/letsencrypt NPM_DATA_PATH="${NPM_DATA_PATH:-}" NPM_LETSENCRYPT_PATH="${NPM_LETSENCRYPT_PATH:-}" # Retention: keep last N backups RETENTION_COUNT="${RETENTION_COUNT:-7}" # Compression level (1-9, higher = smaller but slower) COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}" # ============================================================================= # INTERNAL VARIABLES # ============================================================================= TIMESTAMP=$(date +"%Y%m%d_%H%M%S") BACKUP_DIR="${BACKUP_DEST}/npm_backup_${TIMESTAMP}" mkdir -p "${BACKUP_DIR}" LOG_FILE="${BACKUP_DIR}/backup.log" # Debug: show config values echo "DEBUG: BACKUP_DEST='${BACKUP_DEST}'" >&2 echo "DEBUG: BACKUP_DIR='${BACKUP_DIR}'" >&2 # Colors for output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # ============================================================================= # HELPER FUNCTIONS # ============================================================================= log() { local level="$1" shift local msg="$*" local timestamp=$(date +"%Y-%m-%d %H:%M:%S") echo -e "${timestamp} [${level}] ${msg}" | tee -a "${LOG_FILE}" } info() { log "INFO" "${BLUE}$*${NC}"; } warn() { log "WARN" "${YELLOW}$*${NC}"; } error() { log "ERROR" "${RED}$*${NC}"; } success() { log "SUCCESS" "${GREEN}$*${NC}"; } die() { error "$*" exit 1 } # ============================================================================= # VALIDATION FUNCTIONS # ============================================================================= validate_paths() { info "Validating data paths..." local has_paths=false if [[ -n "${NPM_DATA_PATH}" ]] && [[ -d "${NPM_DATA_PATH}" ]]; then info "Found data path: ${NPM_DATA_PATH}" has_paths=true elif [[ -n "${NPM_DATA_PATH}" ]]; then warn "Data path does not exist: ${NPM_DATA_PATH}" fi if [[ -n "${NPM_LETSENCRYPT_PATH}" ]] && [[ -d "${NPM_LETSENCRYPT_PATH}" ]]; then info "Found letsencrypt path: ${NPM_LETSENCRYPT_PATH}" has_paths=true elif [[ -n "${NPM_LETSENCRYPT_PATH}" ]]; then warn "Letsencrypt path does not exist: ${NPM_LETSENCRYPT_PATH}" fi if [[ "${has_paths}" == "false" ]]; then info "No explicit paths set, trying to auto-detect..." detect_paths fi if [[ "${has_paths}" == "false" ]]; then die "No valid NPM data paths found. Please set NPM_DATA_PATH, NPM_LETSENCRYPT_PATH environment variables to the dataset paths configured in your NPM app." fi } detect_paths() { local common_bases=( "/mnt/tank/apps/nginx-proxy-manager" "/mnt/tank/apps/npm" "/mnt/pool/apps/nginx-proxy-manager" "/mnt/pool/apps/npm" "/mnt/data/apps/nginx-proxy-manager" "/mnt/data/apps/npm" "/mnt/storage/apps/nginx-proxy-manager" "/mnt/storage/apps/npm" "/mnt/apps/nginx-proxy-manager" "/mnt/apps/npm" ) for base in "${common_bases[@]}"; do if [[ -d "${base}" ]]; then info "Found potential base path: ${base}" if [[ -d "${base}/data" ]] && [[ -z "${NPM_DATA_PATH}" ]]; then NPM_DATA_PATH="${base}/data" info "Auto-detected data: ${NPM_DATA_PATH}" fi if [[ -d "${base}/letsencrypt" ]] && [[ -z "${NPM_LETSENCRYPT_PATH}" ]]; then NPM_LETSENCRYPT_PATH="${base}/letsencrypt" info "Auto-detected letsencrypt: ${NPM_LETSENCRYPT_PATH}" fi if [[ -n "${NPM_DATA_PATH}" ]] || [[ -n "${NPM_LETSENCRYPT_PATH}" ]]; then return 0 fi fi done } validate_database() { info "Validating database connection..." if [[ "${DB_TYPE}" == "sqlite" ]]; then # SQLite database is typically in the data path local sqlite_db="${NPM_DATA_PATH}/database.sqlite" if [[ -f "${sqlite_db}" ]]; then info "Found SQLite database: ${sqlite_db}" if ! sqlite3 "${sqlite_db}" "SELECT 1;" >/dev/null 2>&1; then die "Cannot read SQLite database at ${sqlite_db}. Check permissions." fi success "SQLite database validated" else warn "SQLite database not found at ${sqlite_db} (will be backed up with data path)" fi return 0 fi # MariaDB if [[ -z "${DB_PORT}" ]]; then DB_PORT="3306" fi if [[ -z "${DB_PASS}" ]]; then warn "DB_PASS not set. Trying to find it..." find_db_password fi if [[ -z "${DB_PASS}" ]]; then die "Database password (DB_PASS) is required for MariaDB. Please set it or ensure it can be auto-detected." fi local dump_cmd="" if command -v mariadb-dump >/dev/null 2>&1; then dump_cmd="mariadb-dump" elif command -v mysqldump >/dev/null 2>&1; then dump_cmd="mysqldump" fi if [[ -n "${dump_cmd}" ]]; then export MYSQL_PWD="${DB_PASS}" if ! ${dump_cmd} -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" -e "SELECT 1" >/dev/null 2>&1; then unset MYSQL_PWD die "Cannot connect to MariaDB/MySQL at ${DB_HOST}:${DB_PORT} as ${DB_USER}. Check credentials and ensure database is accessible from host." fi unset MYSQL_PWD else # No host tools, try docker exec info "Host mariadb-dump/mysqldump not found, trying docker exec..." if ! command -v docker >/dev/null 2>&1; then die "Neither mariadb-dump/mysqldump nor docker found. Cannot dump database." fi local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|npm.*db)' | head -1 || true) if [[ -z "${db_container}" ]]; then die "No MariaDB/MySQL container found. Cannot dump database." fi info "Using database container: ${db_container}" if ! docker exec "${db_container}" mariadb -u "${DB_USER}" -p"${DB_PASS}" -e "SELECT 1" >/dev/null 2>&1; then die "Cannot connect to MariaDB/MySQL in container ${db_container}. Check credentials." fi fi success "MariaDB database connection validated" } find_db_password() { local possible_files=( "/mnt/tank/apps/nginx-proxy-manager/.env" "/mnt/tank/apps/npm/.env" "/mnt/pool/apps/nginx-proxy-manager/.env" "/mnt/pool/apps/npm/.env" "/mnt/data/apps/nginx-proxy-manager/.env" "/mnt/data/apps/npm/.env" "/mnt/storage/apps/nginx-proxy-manager/.env" "/mnt/storage/apps/npm/.env" "/mnt/apps/nginx-proxy-manager/.env" "/mnt/apps/npm/.env" "/etc/npm/db_password" "/root/.npm_db_password" ) for file in "${possible_files[@]}"; do if [[ -f "${file}" ]]; then local pass=$(grep -iE '(password|passwd)' "${file}" 2>/dev/null | head -1 | sed -E 's/.*[=:]\s*//' | sed -E 's/["\'"'"']//g' | xargs) if [[ -n "${pass}" ]]; then DB_PASS="${pass}" info "Found database password in ${file}" return 0 fi fi done if command -v docker >/dev/null 2>&1; then local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|npm.*db)' | head -1 || true) if [[ -n "${db_container}" ]]; then info "Found potential DB container: ${db_container}" local pass=$(docker inspect "${db_container}" 2>/dev/null | grep -iE '(MYSQL_PASSWORD|MARIADB_PASSWORD)' | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true) if [[ -n "${pass}" ]]; then DB_PASS="${pass}" info "Found database password from container env" return 0 fi fi fi } # ============================================================================= # BACKUP FUNCTIONS # ============================================================================= backup_database() { if [[ "${DB_TYPE}" == "sqlite" ]]; then info "SQLite database will be backed up as part of data directory" return 0 fi info "Backing up MariaDB database..." local db_dump="${BACKUP_DIR}/database/npm_${TIMESTAMP}.sql" mkdir -p "${BACKUP_DIR}/database" local dump_cmd="" if command -v mariadb-dump >/dev/null 2>&1; then dump_cmd="mariadb-dump" elif command -v mysqldump >/dev/null 2>&1; then dump_cmd="mysqldump" fi if [[ -n "${dump_cmd}" ]]; then info "Using ${dump_cmd} for database dump" local conn_params=( "-h" "${DB_HOST}" "-P" "${DB_PORT}" "-u" "${DB_USER}" "--single-transaction" "--routines" "--triggers" "--events" "--hex-blob" "--complete-insert" "--extended-insert" "--quick" "--lock-tables=false" ) export MYSQL_PWD="${DB_PASS}" if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then unset MYSQL_PWD die "Database dump failed" fi unset MYSQL_PWD else # Use docker exec info "Host mariadb-dump/mysqldump not found, using docker exec..." if ! command -v docker >/dev/null 2>&1; then die "Neither mariadb-dump/mysqldump nor docker found. Cannot dump database." fi local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|npm.*db)' | head -1 || true) if [[ -z "${db_container}" ]]; then die "No MariaDB/MySQL container found. Cannot dump database." fi info "Using docker exec on container: ${db_container}" info "Dumping database ${DB_NAME}..." if ! docker exec "${db_container}" mariadb-dump -u "${DB_USER}" -p"${DB_PASS}" \ --single-transaction --routines --triggers --events --hex-blob \ --complete-insert --extended-insert --quick --lock-tables=false \ "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then die "Database dump failed via docker exec." fi fi info "Compressing database dump..." gzip -${COMPRESSION_LEVEL} "${db_dump}" db_dump="${db_dump}.gz" local size=$(du -h "${db_dump}" | cut -f1) success "Database backup complete: ${db_dump} (${size})" } backup_directory() { local src_path="$1" local dest_subdir="$2" local description="$3" info "Backing up ${description}..." local dest_dir="${BACKUP_DIR}/${dest_subdir}" mkdir -p "${dest_dir}" if [[ ! -d "${src_path}" ]]; then warn "Source path does not exist: ${src_path}" return 0 fi info "Copying from ${src_path} to ${dest_dir}..." if ! rsync -av "${src_path}/" "${dest_dir}/" 2>&1 | tee -a "${LOG_FILE}"; then warn "Failed to copy data from ${src_path}" return 1 fi local count=$(find "${dest_dir}" -type f | wc -l) local size=$(du -sh "${dest_dir}" | cut -f1) success "${description} backup complete: ${count} files, ${size}" } create_archive() { info "Creating compressed archive..." local archive_name="npm_backup_${TIMESTAMP}.tar.gz" local archive_path="${BACKUP_DEST}/${archive_name}" tar -czf "${archive_path}" -C "${BACKUP_DEST}" "npm_backup_${TIMESTAMP}" 2>>"${LOG_FILE}" local size=$(du -h "${archive_path}" | cut -f1) success "Archive created: ${archive_path} (${size})" sha256sum "${archive_path}" > "${archive_path}.sha256" info "SHA256: $(cat "${archive_path}.sha256")" info "Cleaning up uncompressed backup directory..." rm -rf "${BACKUP_DIR}" echo "${archive_path}" } cleanup_old_backups() { info "Cleaning up old backups (keeping last ${RETENTION_COUNT})..." cd "${BACKUP_DEST}" ls -1t npm_backup_*.tar.gz 2>/dev/null | tail -n +$((RETENTION_COUNT + 1)) | while read -r file; do info "Removing old backup: ${file}" rm -f "${file}" "${file}.sha256" done success "Cleanup complete" } generate_restore_info() { info "Generating restore information..." cat > "${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" < 3. Follow the prompts Database Connection for Docker: - SQLite (default): No extra config needed, database file in data/ - MariaDB: - Host: (usually 'db' in docker-compose) - Port: 3306 - Database: npm - User: npm - Password: Volume Mounts for Docker: - ./npm-data:/data - data/ -> /data/ (config, database, custom SSL) - letsencrypt/ -> /etc/letsencrypt/ (SSL certificates) Important NPM-specific notes: 1. NPM runs as root in container (UID 0) - permissions are less strict 2. After restore, you may need to update IP addresses in proxy hosts if changed 3. SSL certificates in letsencrypt/ should work automatically 4. Check /data/config/production.json for database settings 5. Default admin email: admin@example.com / password: changeme (change on first login!) Source Paths Used: - Data: ${NPM_DATA_PATH:-} - Let's Encrypt: ${NPM_LETSENCRYPT_PATH:-} EOF success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" } # ============================================================================= # MAIN EXECUTION # ============================================================================= main() { info "======================================" info "Nginx Proxy Manager TrueNAS 27+ App Backup Started" info "======================================" info "Timestamp: ${TIMESTAMP}" info "Backup destination: ${BACKUP_DEST}" info "Backup directory: ${BACKUP_DIR}" validate_paths validate_database backup_database backup_directory "${NPM_DATA_PATH}" "data" "Data directory" backup_directory "${NPM_LETSENCRYPT_PATH}" "letsencrypt" "Let's Encrypt certificates" local archive=$(create_archive) cleanup_old_backups generate_restore_info info "======================================" success "Backup completed successfully!" info "======================================" info "Archive: ${archive}" info "Checksum: ${archive}.sha256" info "Restore info: ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" info "" info "Next steps:" info "1. Copy ${archive} to your Docker host" info "2. Run the restore script on the Docker host" info "3. Verify the restored Nginx Proxy Manager instance" } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main "$@" fi