Skip to content

Backup architecture

Developer guide for SimpleDeploy’s backup module. Covers architecture, data flow, extension points, and known limitations.

The backup system has three layers:

UI (Svelte) --> API (Go handlers) --> Scheduler (cron + orchestration)
|
Strategy + Target (pluggable)
|
Store (SQLite)

Strategy defines what to back up (postgres dump, volume tar). Target defines where to store it (local filesystem, S3). Scheduler wires them together, runs cron jobs, handles retention. The API exposes CRUD for configs/runs plus manual triggers. The UI provides a wizard for config creation and a dashboard for monitoring.

Both are in internal/backup/.

// Strategy defines how to back up and restore data.
type Strategy interface {
Backup(ctx context.Context, containerName string) (io.ReadCloser, string, error)
Restore(ctx context.Context, containerName string, data io.Reader) error
}
// Target defines where backup data is stored.
type Target interface {
Upload(ctx context.Context, filename string, data io.Reader) (int64, error)
Download(ctx context.Context, filename string) (io.ReadCloser, error)
Delete(ctx context.Context, filename string) error
}

Strategies produce a data stream + filename. Targets move that stream to/from storage. This separation means any strategy works with any target.

Runs docker exec <container> sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB"' and gzip-compresses the output. The user and database are read from the container’s env at dump time, so the strategy works with the stock postgres image (which would otherwise dump the empty default postgres database). Override via opts.Credentials["POSTGRES_USER"]. Restore pipes the gzipped dump into psql using the same user/db resolution.

Filename: {containerName}-{YYYYMMDD-HHMMSS}.sql.gz

Runs docker exec <container> tar -czf - <paths...> against the paths configured on the backup config. Tar strips leading / so the archive contents are relative (e.g. var/lib/postgresql/data/...). Restore extracts with tar -xzf - -C /, which recreates the absolute paths. Filename: {containerName}-{YYYYMMDD-HHMMSS}.tar.gz

Caveat for running databases. Backing up a live postgres data directory produces a crash-consistent snapshot, but a volume restore over the same directory is racy because pg keeps files open. Use the dedicated DB strategy (postgres/mysql/mongo/redis) that speaks the protocol. Stop/start hooks cannot help here: the volume backup and restore run tar inside the service’s own container, so that service must stay running. Hooks can stop other services that write to the data (see Backup hooks).

MySQL / MariaDB (internal/backup/mysql.go)

Section titled “MySQL / MariaDB (internal/backup/mysql.go)”

docker exec <c> sh -c 'mysqldump --all-databases -u root -p"$MYSQL_ROOT_PASSWORD"'. The root password is read from the container env at dump time (same idea as postgres), so the stock mysql:8 / mariadb images work out of the box. Restore pipes the gzipped SQL into mysql -u root -p$MYSQL_ROOT_PASSWORD. Override via opts.Credentials["MYSQL_ROOT_PASSWORD"]. Filename: {containerName}-{YYYYMMDD-HHMMSS}.sql.gz.

docker exec <c> sh -c 'mongodump --archive --gzip --authenticationDatabase admin -u "$MONGO_INITDB_ROOT_USERNAME" -p "$MONGO_INITDB_ROOT_PASSWORD"'. Credentials are read from the container env. Restore uses mongorestore --drop so it overwrites existing collections. Override via opts.Credentials["MONGO_INITDB_ROOT_USERNAME"] / ["MONGO_INITDB_ROOT_PASSWORD"]. Filename: {containerName}-{YYYYMMDD-HHMMSS}.archive.gz.

Captures the pre-BGSAVE LASTSAVE timestamp, triggers BGSAVE, polls until the timestamp changes, then docker cps /data/dump.rdb out and gzips it. Restore stops the container, docker cps the decompressed rdb back into /data/, and restarts. Filename: {containerName}-{YYYYMMDD-HHMMSS}.rdb.gz.

Detected via the simpledeploy.backup.strategy=sqlite label on a service. Backup() runs docker exec <c> sqlite3 <path> .backup /tmp/... using the explicit path from the backup config (paths: ["/data/app.db"]). The Detect method returns the mounted volume directory but not the DB filename — configs must specify the concrete .db file path. Filename: {containerName}-{YYYYMMDD-HHMMSS}.db.gz.

Writes files to {dataDir}/backups/ on the host filesystem. Files created with mode 0600. Validates filenames against path traversal (.., absolute paths).

Stores in any S3-compatible service (AWS, MinIO, DigitalOcean Spaces, Backblaze B2). Config:

type S3Config struct {
Endpoint string `json:"endpoint"` // empty for AWS S3
Bucket string `json:"bucket"`
Prefix string `json:"prefix"` // optional key prefix (e.g. "backups/myapp")
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
Region string `json:"region"` // defaults to "us-east-1"
}

target_config_json (and the test-s3 body) uses the snake_case keys the UI sends. S3Config.UnmarshalJSON also accepts the Go field names (AccessKey, SecretKey; the other fields match case-insensitively) because configs created before the struct had tags were stored that way. Every decode path (config validation, test-s3, the download presigner, the scheduler’s target factory) decodes into S3Config with encoding/json, so they all share this parsing.

Uses AWS SDK v2 with the feature/s3/manager Uploader for PutObject. The manager handles non-seekable readers (strategies stream through a gzip.Writer piped from pg_dump/mysqldump/tar stdout, which are not seekable — the plain PutObject would fail trying to compute a payload hash). Path-style addressing is enabled when a custom Endpoint is set so MinIO, DigitalOcean Spaces, and Backblaze B2 all work.

Custom endpoints are restricted to public addresses unless SIMPLEDEPLOY_ALLOW_PRIVATE_S3=1:

  • ValidateS3Endpoint runs when a config is created or updated and on test-s3. The endpoint must be an http(s):// URL, and every address its host resolves to must be public (isReservedIP: loopback, private, link-local, CGNAT, multicast, documentation and other reserved ranges; NAT64 64:ff9b::/96 judged by the embedded IPv4).
  • NewS3Target installs an HTTP client whose dialer checks each IP right before connect() (s3DialControl), so DNS changes after validation are covered. A blocked dial fails with ErrS3EndpointBlocked and is not retried.
  • HTTP_PROXY/HTTPS_PROXY/NO_PROXY are honoured. Connections to the configured proxy skip the dial check (the proxy resolves the endpoint), so when the endpoint is proxied NewS3Target re-runs ValidateS3Endpoint every time the target is built.

Orchestrates everything. Created at startup, receives registered strategies and target factories.

sched := backup.NewScheduler(db)
sched.RegisterStrategy("postgres", backup.NewPostgresStrategy())
sched.RegisterStrategy("volume", backup.NewVolumeStrategy("/data"))
sched.RegisterTargetFactory("local", func(configJSON string) (backup.Target, error) { ... })
sched.RegisterTargetFactory("s3", func(configJSON string) (backup.Target, error) { ... })
sched.Start() // loads configs, schedules cron jobs
  1. Fetch config from DB
  2. Create run record (status=running)
  3. Look up strategy and target factory by name
  4. Instantiate target from TargetConfigJSON
  5. Get app name for container naming (compose project simpledeploy-<slug>)
  6. planRun: validate the paths for volume/sqlite (validateRunPaths) and the hooks (CheckHooks), before any hook runs
  7. Run pre-hooks (see Hooks)
  8. Call strategy.Backup() to get data stream
  9. Call target.Upload() to store it, then run post-hooks
  10. Update run to success with size and file path
  11. Prune old runs beyond the retention limit (RetentionCount, or RetentionDays in time mode): delete each file from the target, then the run row (DeleteBackupRun), so pruned runs are not offered for download/restore or pruned again. A file already missing counts as deleted; any other delete error keeps the row for the next prune to retry
  12. On any error: update run to failed with error message
  1. Fetch run and its config from DB
  2. Get strategy and target; resolve the container and paths as for a backup, then validate the paths and hooks (planRun)
  3. Call target.Download() to retrieve data
  4. If the run has a checksum, spool the download to a temp file while hashing it, and fail on mismatch before anything is applied (Pipeline.RunRestore)
  5. Run pre-hooks, call strategy.Restore() to apply it (with MaxDecompressedBytes from runRestoreMaxBytes()), then run post-hooks

Both backup and restore run asynchronously (fired via go in API handlers).

Container scoping. POST /api/apps/{slug}/backups/upload-restore resolves its container field with resolveRestoreContainer: it lists containers labelled com.docker.compose.project=simpledeploy-<slug> (re-checking the label) and accepts only an exact container name, an ID or ID prefix of 12+ characters, or a compose service name from that list. Empty falls back to the slug or to the app’s only container. Anything else is a 400 listing the app’s services. Restores from a backup run use the container detected from the app’s own compose file (falling back to the app name).

Archive validation and staging. volume, sqlite and redis restores pass the stream through validateTarStream (tarsafe.go) before anything is extracted or the container is stopped. It copies the archive to a spool file and walks every tar header (checkTarEntry rejects empty or absolute names, .. traversal, NUL bytes, symlinks and hardlinks, and device/fifo entries). Spool files live in the directory set by SetSpoolDir, which serve and the CLI backup commands point at {data_dir}/tmp (created and kept 0700), else the system temp dir. Each file is 0600, unlinked right after creation where the OS allows it, and removed on close. A checksum-verified spool from RunRestore is validated in place instead of copied. Uploads are saved to {data_dir}/tmp too, after a restore slot is acquired.

Size limits. MaxDecompressedBytes caps both the raw archive and its decompressed stream (including bytes after the tar end marker); going over fails with errArchiveTooLarge instead of truncating. 0 means 8 GiB, negative (NoDecompressedLimit) means no cap. Uploads use UploadRestoreMaxBytes() (8 GiB, or SIMPLEDEPLOY_RESTORE_MAX_GB); backup-run restores use runRestoreMaxBytes() (no cap unless the variable is set). postgres, mysql and redis also wrap their gzip reader with limitedGzip.

Concurrency. Server.restoreSem (capacity 4) is shared by upload restores and POST /api/backups/restore/{id}. A full semaphore returns 429 with “too many restores in progress, try again later”; uploads are rejected before they touch disk.

Config validation. validateBackupConfig runs on create and update and returns 400 with a readable message: ValidateCron (same parser as the scheduler), ValidatePathsConfig (absolute, clean, not /, no control characters, no element starting with -; SQLite paths must name a file and may not contain quotes, backslash, backtick or $), and ValidateS3Endpoint. The volume strategy also passes -- to tar so no path is read as a flag.

pre_hooks / post_hooks on a config are JSON lists of {type, service, command, timeout} (hooks.go). Types: stop, start, exec (sh -c <command>), flush_redis, flush_mysql. User guide: Backup hooks.

Scoping. HookRunner is built per run with the app’s compose project (simpledeploy-<slug>) and passes it with every call to ContainerExecutor, whose methods take (project, service), never a container name. DockerHookExecutor (hookexec.go, wired in serve and the CLI backup commands) lists containers filtered by the com.docker.compose.project and com.docker.compose.service labels, re-checks both labels on each result, skips one-off (compose run) containers, and runs docker exec <id> sh -c, docker stop <id> or docker start <id> by container ID. A service with no matching container is a hook error. So a hook can never reach another app, SimpleDeploy itself, or other host containers, whatever the stored config says. stop/start act on every replica; exec uses the lowest-numbered running one.

Validation. CheckHooks (parse with ParseHooks, then ValidateHooks): known type, non-empty service that is a service in the app’s compose file, timeout 0 to MaxHookTimeout (3600s, 0 = 30s), exec needs a command, command at most MaxHookCommandLen (4096) with no NUL, at most MaxHooks (20) per list, and no pre-hook stop of a service the strategy detects (the strategy runs docker exec in it). The API (validateBackupHooks) runs it on create/update, answers 400 with the message, and stores the hooks in canonical form (HooksJSON); hooks need a readable compose file. planRun runs it again before each backup/restore because hooks can also arrive through sidecars and git sync (configsync writes them unchecked); an invalid hook fails the run before anything executes. Entries whose service is an object (saved by the old wizard, never run) are skipped with a log line and dropped on the next save.

Failure semantics. Pre-hooks run in order and the first failure aborts (RunPre); the run fails, and post-hooks still run so a stopped service is started again. Post-hooks run after success or failure with cancellation removed (context.WithoutCancel); failures are logged warnings (PipelineResult.Warnings) and never fail the run. Hooks set while no executor is configured fail the run instead of being skipped.

Column Type Notes
id INTEGER PK Auto-increment
app_id INTEGER FK to apps
strategy TEXT postgres or volume
target TEXT s3 or local
schedule_cron TEXT 5-field cron expression
target_config_json TEXT JSON config for target (S3 creds, etc.)
retention_count INTEGER Keep last N successful backups (default 7)
created_at DATETIME Auto-set
Column Type Notes
id INTEGER PK Auto-increment
backup_config_id INTEGER FK to backup_configs
status TEXT running, success, or failed
size_bytes INTEGER Nullable, set on success
started_at DATETIME Auto-set
finished_at DATETIME Nullable, set on completion
error_msg TEXT Nullable, set on failure
file_path TEXT Nullable, relative path/key of backup file

All require auth via authMiddleware.

Method Path Handler Purpose
GET /api/apps/{slug}/backups/configs handleListBackupConfigs List configs for app
POST /api/apps/{slug}/backups/configs handleCreateBackupConfig Create config (validated)
PUT /api/backups/configs/{id} handleUpdateBackupConfig Update config (validated)
DELETE /api/backups/configs/{id} handleDeleteBackupConfig Delete config
GET /api/apps/{slug}/backups/runs handleListBackupRuns List runs across all app configs
POST /api/apps/{slug}/backups/run handleTriggerBackup Trigger backup (first config)
POST /api/backups/configs/{id}/run handleTriggerBackupConfig Trigger backup for specific config
POST /api/backups/restore/{id} handleRestore Restore from a run (202 async, 429 when 4 restores run)
POST /api/apps/{slug}/backups/upload-restore handleUploadRestore Restore an uploaded file into one of the app’s containers (202 async)
GET /api/backups/summary handleBackupSummary Cross-app dashboard data
GET /api/apps/{slug}/backups/detect handleDetectStrategies Auto-detect available strategies
POST /api/backups/test-s3 handleTestS3 Validate S3 credentials

/api/apps/{slug}/backups/detect parses the app’s compose file and inspects services:

  • Checks image names for postgres to detect database containers
  • Collects volume mounts (excluding /var/run/docker.sock)
  • Returns strategy availability with container/volume details

/backups Dashboard (ui/src/routes/Backups.svelte)

Section titled “/backups Dashboard (ui/src/routes/Backups.svelte)”

Cross-app overview. Calls GET /api/backups/summary which returns:

  • Per-app health: config count, strategies, last run status, storage used, 24h success/fail counts
  • Recent runs across all apps with app name and strategy

Renders summary stat cards, per-app health cards (BackupHealthCard), and a filterable activity feed.

App Detail > Backups Tab (ui/src/components/BackupsTab.svelte)

Section titled “App Detail > Backups Tab (ui/src/components/BackupsTab.svelte)”

Per-app backup management. Three states:

  1. Empty: no configs, shows CTA to configure
  2. Has configs: status header + config table + run history
  3. Loading: skeleton placeholders

Config table shows friendly labels (e.g. “Database (PostgreSQL)” not “postgres”, “Daily at 02:00” not “0 2 * * *”).

Backup Wizard (ui/src/components/BackupWizard.svelte)

Section titled “Backup Wizard (ui/src/components/BackupWizard.svelte)”

6-step FormModal:

  1. What to back up: auto-detects strategies from compose, shows availability
  2. Where to store: local or S3 with inline config form + connection test
  3. Schedule: visual cron builder (ScheduleBuilder component)
  4. Hooks: optional custom pre/post commands (service name + command, saved as exec hooks). Stored hooks in the old object-service format are dropped on load
  5. Retention: count or days, plus upload verification
  6. Review: summary of all selections

Schedule Builder (ui/src/components/ScheduleBuilder.svelte)

Section titled “Schedule Builder (ui/src/components/ScheduleBuilder.svelte)”

Visual cron builder with 4 modes: daily (time picker), weekly (day chips + time), monthly (day-of-month + time), custom (raw cron input). Shows human-readable preview and generated cron expression.

  1. Create internal/backup/mystrategy.go, implementing the Strategy interface:
type MyStrategy struct{}
func NewMyStrategy() *MyStrategy { return &MyStrategy{} }
func (s *MyStrategy) Type() string { return "mystrategy" }
func (s *MyStrategy) Detect(cfg *compose.AppConfig) []DetectedService {
// Inspect compose services for image keywords or a
// `simpledeploy.backup.strategy=mystrategy` label.
// IMPORTANT: ContainerName must be `<project>-<service>-1` where project is
// `cfg.Name` (the scheduler passes "simpledeploy-<app.Slug>" as cfg.Name,
// so the returned name will match the real docker compose container).
return []DetectedService{{ServiceName: "...", ContainerName: cfg.Name+"-...-1"}}
}
func (s *MyStrategy) Backup(ctx context.Context, opts BackupOpts) (*BackupResult, error) {
// Read credentials from opts.Credentials, OR read env from inside the
// container via `docker exec ... sh -c '... $ENV_VAR ...'`.
// Return an io.ReadCloser that streams the backup bytes + a filename.
}
func (s *MyStrategy) Restore(ctx context.Context, opts RestoreOpts) error {
// Pipe opts.Reader into the restore process.
}
  1. Register in cmd/simpledeploy/main.go (newBackupScheduler):
sched.RegisterStrategy("mystrategy", backup.NewMyStrategy())
  1. Add to migration 015 CHECK constraint (or a new migration) to allow the new strategy name.

  2. Update UI wizard labels in ui/src/components/BackupWizard.svelte (strategyLabel map + icons).

Strategies that need DB credentials have two sources in priority order:

  1. opts.Credentials["KEY"] — explicitly set by the caller (future-proofing for when the scheduler inspects container env)
  2. Container env via docker exec ... sh -c '... $ENV_VAR ...' — works out of the box with official images (postgres, mysql:8, mongo:7)

The scheduler currently does NOT populate opts.Credentials from container inspection. All strategies must work with the container-env fallback.

  1. Create internal/backup/mytarget.go implementing the Target interface.

  2. Register factory in cmd/simpledeploy/main.go:

sched.RegisterTargetFactory("mytarget", func(configJSON string) (backup.Target, error) {
var cfg MyTargetConfig
json.Unmarshal([]byte(configJSON), &cfg)
return NewMyTarget(cfg)
})
  1. Add to migration CHECK constraint.

  2. Update wizard step 2 with UI for the new target’s config fields.

Separate from app backups. Lives in internal/store/db_backup.go and internal/api/system.go. Uses SQLite VACUUM INTO for atomic, consistent copies. Supports a “compact” mode that strips metrics/request_stats tables to reduce size. Managed from the System page, not the Backups page.

  • Trigger backup uses first config: the per-app trigger (POST /apps/{slug}/backups/run) only runs the first config; use config-specific trigger (POST /backups/configs/{id}/run) to pick a specific one
  • Volume restore over running DB is racy: use DB-native strategy (postgres/mysql/mongo/redis). Hooks cannot stop the service the volume strategy runs tar in
  • Let’s Encrypt backup target: none; S3 and local only. For any other object storage, implement a new Target
internal/backup/
strategy.go Strategy interface
target.go Target interface
scheduler.go Scheduler (cron, RunBackup, RunRestore)
pipeline.go Hooks + checksum-verified restore spooling
hooks.go Hook types, HookRunner, parsing and validation
hookexec.go DockerHookExecutor (project/service-scoped docker exec/stop/start)
paths.go Path and cron validation
tarsafe.go Restore archive validation, spool files, size cap
postgres.go PostgreSQL strategy (pg_dump/psql)
volume.go Volume strategy (tar)
local.go Local filesystem target
s3.go S3-compatible target
internal/store/
backups.go BackupConfig/BackupRun CRUD + summary queries
db_backup.go System DB backup operations
migrations/
007_backups.sql backup_configs + backup_runs tables
011_db_backup.sql db_backup_config + db_backup_runs tables
internal/api/
backups.go All backup API handlers
server.go Route registration (lines 227-241)
cmd/simpledeploy/
main.go Scheduler init (newBackupScheduler), CLI commands
ui/src/
routes/Backups.svelte Cross-app dashboard
components/BackupsTab.svelte Per-app backup management
components/BackupWizard.svelte 4-step config creation wizard
components/BackupHealthCard.svelte Dashboard health card
components/ScheduleBuilder.svelte Visual cron builder
lib/api.js API client methods