#!/usr/bin/env bash # Nightly backup for the n8n compose stack: database dump + workflow/credential export + encryption key. # Tested 2026-11-11 with n8n 2.47.3 and postgres:18. Run from the folder that holds compose.yaml. # Cron example (03:15 every night): 15 3 * * * cd /opt/n8n && ./backup.sh >> backups/backup.log 2>&1 set -euo pipefail cd "$(dirname "$0")" set -a; . ./.env; set +a STAMP=$(date +%Y-%m-%d_%H%M) DEST="backups/$STAMP" KEEP_DAYS=${KEEP_DAYS:-14} mkdir -p "$DEST" # 1. Full database (users, settings, executions, encrypted credentials) docker compose exec -T postgres pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --format=custom > "$DEST/n8n-db.dump" # 2. Workflows and credentials as separate JSON files (still encrypted) docker compose exec -T n8n sh -c 'rm -rf /tmp/export && n8n export:workflow --backup --output=/tmp/export/workflows/ && n8n export:credentials --backup --output=/tmp/export/credentials/' >/dev/null docker compose cp n8n:/tmp/export/. "$DEST/" docker compose exec -T n8n rm -rf /tmp/export # 3. The key that decrypts the credentials printf 'N8N_ENCRYPTION_KEY=%s\n' "$N8N_ENCRYPTION_KEY" > "$DEST/encryption-key.txt" chmod 600 "$DEST/encryption-key.txt" # 4. Check: the dump must not be empty, and at least the folders exist test -s "$DEST/n8n-db.dump" || { echo "$STAMP backup FAILED: empty database dump"; exit 1; } # 5. Remove backups older than KEEP_DAYS find backups -mindepth 1 -maxdepth 1 -type d -mtime +"$KEEP_DAYS" -exec rm -rf {} + echo "$STAMP backup ok: $(du -sh "$DEST" | cut -f1)" # Copy the backups folder off this server (another machine, object storage). A backup on the same disk is not a backup.