Skip to content

Backup & Restore

The operator backs up a Nextcloud instance in two halves, both written to the same S3 bucket under the same per-instance prefix:

Half What it holds Mechanism Guide
Database The PostgreSQL cluster, continuously pgBackRest repo2 (S3), managed by Percona Managed PostgreSQL
Configuration config/, encryption keys, declarative state, operator-owned Secrets, custom apps, themes Encrypted bundle uploaded by the operator This page

You need both halves

A database dump restored into a fresh instance is unusable without config/config.php's instanceid, secret and passwordsalt. Restore the configuration bundle first, then the database.

Neither half covers the tenant's file data in the S3 data bucket, or local data/ volumes. Those are separate concerns — see What is not backed up.

<bucket>/
└── <namespace>/
    └── <instance-name>/
        └── backups/
            ├── db/              ← pgBackRest repo2 (Percona writes this)
            └── config/
                ├── 20260825T031500Z.tar.enc
                └── 20260826T031500Z.tar.enc

The configuration bundle

What is in it

Priority-ordered — the first two are the ones no restore works without:

# Item Why it matters
1 config/ — the whole directory, not just config.php (so every *.config.php drop-in comes too) Holds instanceid, secret and passwordsalt. Without them there is no restore, only a new instance.
2 data/files_encryption/, when the server-side encryption app is active Encrypted files are unrecoverable noise without the keys.
3 Declarative state — the Nextcloud CR, the NextcloudInstance spec, the applied profile, and the operator/chart/Nextcloud versions Rebuild the instance shell on a clean cluster; input for restore tooling.
4 Operator-owned Secrets — admin, mail, the S3 data-bucket credentials, the OIDC client secret Reattach primary storage and accounts without credential archaeology.
5 custom_apps/ Store apps are re-installable, but version drift is real and genuinely custom apps are in no store.
6 themes/ Custom theming is not reproducible from the spec.
7 manifest.json — inventory, per-item SHA-256 checksums, versions, warnings How a restore drill verifies what it actually got.

Inline credentials in the captured spec (item 3) are replaced with a redaction marker: the real values live in item 4, exactly once.

What is not backed up

Not included Where it belongs instead
The tenant's files in the S3 data bucket Bucket versioning / replication, or the restic backups.data path
Local data/ volumes (other than the encryption keys) Volume snapshots
data/appdata* previews and caches Regenerated on demand
Redis contents Cache — nothing to restore
The HelmRelease and rendered values Regenerated from the spec
Database dumps pgBackRest owns the database

When it runs

  • Daily, at a per-instance hour derived from a stable hash of the instance name, so a whole estate does not upload to one bucket in the same minute.
  • Once immediately after pool assignment. A just-assigned instance is the one most likely to be restored soon, and its pre-assignment bundle describes a spare rather than a tenant.

It runs only when both a bucket and an encryption key resolve — see Configuration. No key means no bundle, never an unencrypted one: this artifact carries the config triad, the encryption keys and the operator-owned Secrets.

Configuration

The bucket and key resolve exactly as for the database backups: the merged instance spec first, then the operator's own backup.dbDefaultS3.* values. Configure the operator once and every instance is covered.

Per-instance knobs:

spec:
  backups:
    config:
      enabled: true    # code default: on, whenever a bucket and a key resolve
      retention: 14    # code default: keep 14 bundles, prune older after each upload

Size guard

The bundle streams out of the running pod in bounded chunks and is capped at roughly 200 MiB. Items 1 and 2 (config/, the encryption keys) and items 5 and 6 (custom_apps/, themes/) are streamed separately, so an oversized custom_apps/:

  • drops items 5 and 6 from that bundle,
  • records the reason in manifest.json under warnings, and repeats it on the ConfigBackupCompleted event,
  • still uploads a complete, restorable bundle of everything critical.

An oversized or missing config/ fails the run instead: uploading a bundle that cannot restore, while the freshness metric reports success, would be worse than no bundle at all.

Encryption format

The bundle is an OpenSSL enc container — Salted__ + an 8-byte random salt, key and IV derived with PBKDF2-HMAC-SHA256 (10 000 iterations), AES-256-CBC with PKCS#7 padding. That is deliberately not a bespoke format: a restore happens on someone's worst day, possibly without this operator and without Python, so decryption has to be possible with stock tooling.

enc containers are unauthenticated by design, so integrity is verified against the per-item SHA-256 checksums in manifest.json, not by the container itself.

Security model

Worth stating plainly, because both properties are accepted design, not oversights — if either is unacceptable for a given tenant, give that tenant its own bucket via the per-instance override.

Tenant separation inside a shared bucket is a convention, not enforcement

Every instance's backups live under its own key prefix — /<namespace>/<instance>/backups/db/ and /<namespace>/<instance>/backups/config/ — and that prefix is what keeps one instance's data distinguishable from another's. But with the operator-central default, all instances share one bucket and one S3 credential. Nothing at the object-store layer stops that credential from reading or writing another instance's prefix; separation rests on the operator always constructing the right prefix, not on IAM.

What that does and does not buy you:

  • Tenants themselves have no access. The bucket credential lives in the operator's namespace and is rendered into each instance namespace only in pgBackRest's s3.conf, for the database repo host. A Nextcloud tenant never receives it.
  • A compromise of the operator, or of the shared credential, exposes every instance's backups in that bucket — including the archive of instances unrelated to the breach.
  • A prefix bug is a cross-tenant bug. This is why the operator emits an explicit per-instance repo2-path (Percona would otherwise use one fleet-wide path) and why bundle pruning refuses to act on any key outside the instance's own prefix.

Give a tenant a genuinely isolated bucket — with its own IAM credential scoped to it — by setting database.postgres.backup.s3.bucket on that instance. It overrides the central default for both halves.

Secret-reference confinement

A Secret named by an instance spec always resolves in that instance's own namespace. credentialsFrom.secretRef and encryption.keyFrom.secretRef have no namespace subfield, in the CRD schema or in the operator.

The operator holds cluster-wide read on Secrets while an instance spec is tenant-writable, so honouring a spec-supplied namespace would be a confused deputy: an ordinary CR write would make the operator read any Secret in any namespace — the db-backup-cipher above included — and materialize its contents into a Secret in the tenant's own namespace, where the tenant can read it. The only cross-namespace source is the operator's own Helm values.

Restoring

1. Fetch and decrypt a bundle

NAMESPACE=tenant-example
INSTANCE=nc-happy-sun-a1b2c3
BUCKET=nextcloud-db-backups

# Base prefix: the instance's backup record (see "Backup records"), else /<namespace>/<instance>/backups
# (see "Base prefix" below). The bundles are under <base>/config/.
BASE="$NAMESPACE/$INSTANCE/backups"

# Newest bundle for this instance
aws s3 ls "s3://$BUCKET/$BASE/config/" --endpoint-url https://s3.example.com

aws s3 cp "s3://$BUCKET/$BASE/config/20260825T031500Z.tar.enc" . \
  --endpoint-url https://s3.example.com

# The passphrase is the SAME as the instance's pgBackRest repo2 cipher-pass. With the
# central key and scheme "none" that is the central key itself; with hmac-sha256-v1 it is
# derived from it -- see "Per-instance encryption pass" below for which, and how.
kubectl -n nextcloud-operator-system get secret db-backup-cipher \
  -o jsonpath='{.data.cipher-pass}' | base64 -d > cipher.key
chmod 600 cipher.key

openssl enc -d -aes-256-cbc -pbkdf2 -pass file:cipher.key \
  -in 20260825T031500Z.tar.enc -out bundle.tar

mkdir bundle && tar -xf bundle.tar -C bundle && ls bundle

2. Verify it before trusting it

cd bundle
python3 - <<'EOF'
import hashlib, json
manifest = json.load(open("manifest.json"))
print(manifest["instance"], manifest["timestamp"], manifest["versions"])
for item in manifest["items"]:
    actual = hashlib.sha256(open(item["name"], "rb").read()).hexdigest()
    print(("OK  " if actual == item["sha256"] else "FAIL"), item["name"])
for warning in manifest["warnings"]:
    print("WARNING:", warning)
EOF

Any FAIL, or an unexpected warnings entry, means stop and use another bundle.

3. Rebuild the instance shell

python3 -c "import json;print(json.load(open('bundle/declarative-state.json'))['nextcloudInstance'])"

Re-apply the captured NextcloudInstance (and Nextcloud) spec. Credentials in that copy are redacted — restore them from bundle/secrets.json, which holds the real admin, mail, S3 data-bucket and OIDC values.

Handle the extracted bundle like a live credential

secrets.json and files-critical.tar.gz contain plaintext credentials and the passwordsalt/secret triad. Extract on an encrypted volume, and delete the working directory when you are done.

4. Restore the configuration files

kubectl -n <namespace> cp bundle/files-critical.tar.gz <pod>:/tmp/
kubectl -n <namespace> exec <pod> -- tar -xzf /tmp/files-critical.tar.gz -C /var/www/html
kubectl -n <namespace> exec <pod> -- rm /tmp/files-critical.tar.gz

files-optional.tar.gz (custom apps, themes) restores the same way, if present.

5. Restore the database

The database is restored with pgBackRest through Percona's own restore path, from repo2. Follow the Percona PG Operator restore procedure for the cluster <instance>-pg, selecting repo2 and the backup set nearest the bundle's timestamp. The repository is encrypted with the same passphrase as above (the instance's pass, see Per-instance encryption pass).

6. Verify

kubectl -n <namespace> exec <pod> -- php occ status
kubectl -n <namespace> exec <pod> -- php occ user:list

Write the runbook from a drill, not from this page

Restore steps that have never been executed are a hypothesis. Run a restore drill against a scratch instance, record the real timings, and keep the RTO number that comes out of it — that is what an RPO/RTO commitment can be based on.

S3 bucket versioning

A database-only restore returns the database to an earlier point in time, but files that were deleted from object storage after that point are gone from the bucket. To be able to recover them, the operator can enable versioning on buckets it creates itself.

Operator setting (Helm value) Environment variable Default
s3BucketVersioning.enabled S3_BUCKET_VERSIONING_ENABLED false
s3BucketVersioning.noncurrentVersionDays S3_BUCKET_NONCURRENT_VERSION_DAYS 14

When enabled, a bucket the operator newly creates for an instance gets versioning plus a lifecycle rule noncurrent-expiry that expires noncurrent versions after the configured number of days. Existing buckets and buckets you provide yourself are never modified. A value that is not a positive integer logs a warning and falls back to 14. The flag accepts true in any case, surrounding whitespace is ignored.

Applying versioning never blocks instance creation, so a successful create does not mean versioning is on. Read the outcome:

kubectl -n <namespace> get nci <instance> -o jsonpath='{.status.appliedS3Config.versioning}'
Value Meaning
enabled Versioning and the expiry rule are in place
off The setting is disabled; the bucket is not versioned
failed: <code> The S3 call failed; <code> is the S3 error code (for example AccessDenied), or the exception class for a non-S3 error. The bucket exists unversioned.

The field is absent for instances whose bucket was not created by the operator. Versioned buckets retain deleted-file history for the noncurrent window, which counts toward storage use.

Monitoring

Metric Meaning
nextcloud_operator_config_backup_timestamp_seconds{namespace,instance} Unix timestamp of the last successful bundle upload
pgbackrest_last_backup_completion_timestamp_seconds{namespace,instance,repo,type} Last successful pgBackRest backup, per repository and type

Once S3 is the durable copy, alert on repo="repo2":

# Config bundle older than two days
time() - nextcloud_operator_config_backup_timestamp_seconds > 172800

# No full database backup on S3 in the last 8 days
time() - pgbackrest_last_backup_completion_timestamp_seconds{repo="repo2",type="full"} > 691200

Both series are removed when an instance is deleted, including when a stuck deletion is force-completed by removing the finalizer — so a firing alert always refers to a resource that still exists.

Events

Event Meaning
BackupScheduleApplied The effective database backup configuration changed and was applied
BackupRepo2Bootstrapped The one-time initial full backup on the S3 repository was triggered
BackupRepo2Held The S3 target did not resolve (Secret missing or unreadable, target refused) and the existing repo2 was left unchanged; once per instance
ConfigBackupCompleted A bundle was uploaded; carries the object key, size and any warnings
ConfigBackupFailed A bundle run failed; the reason is redacted of credentials and deduplicated

Status fields

kubectl -n <namespace> get nci <instance> -o jsonpath='{.status.configBackup}' | jq
Field Meaning
configBackup.lastSuccess Timestamp of the last successful upload
configBackup.lastKey Object key of that bundle
configBackup.lastFailure / lastFailureReason Last failure and its redacted reason
configBackup.assignedRunDone The post-assignment bundle has been taken
configBackup.cipherScheme Cipher scheme of the last bundle (none or hmac-sha256-v1); absent when derivation was never configured
backupRepo2Bootstrapped The initial S3 full backup was triggered
backupCipherScheme Cipher scheme the instance's S3 database repository was set up with; absent when derivation was never configured
backupBasePrefix Base prefix the instance's S3 backups were set up under; absent when neither a central path prefix nor derivation was ever configured

A failure never clears lastSuccess or lastKey: that bundle is still in the bucket, and blanking the fields would make one bad day look like "no backups have ever run".

Key custody

Both halves are encrypted with the same passphrase per environment, held in a Secret in the operator's namespace.

  • Generate with openssl rand -base64 48.
  • Store it in the password manager as well as in the cluster. A backup encrypted with a key you have lost is noise.
  • Record in your own runbook where it lives.
  • Rotation is a known limitation of a shared key: rotating it makes existing backups readable only with the old key. Keep retired keys for at least as long as the backups they can open, and record which key covers which date range.

Base prefix: one bucket, one key, separated by path

Every instance's two halves live under one base prefix in the bucket: the pgBackRest repository at <base>/db and the configuration bundles at <base>/config. Without further configuration the base is /<namespace>/<instance>/backups (the layout shown at the top of this page).

backup.dbDefaultS3.pathPrefix (env BACKUP_DB_DEFAULT_S3_PATH_PREFIX) sets the base for every instance that uses the operator-central bucket, as a template with {namespace} and {instance}:

backup:
  dbDefaultS3:
    pathPrefix: "/staging/tenants/{namespace}/{instance}"

renders, for instance nextcloud in namespace nc-x, to /staging/tenants/nc-x/nextcloud: the database repository at /staging/tenants/nc-x/nextcloud/db, the bundles under staging/tenants/nc-x/nextcloud/config/. One bucket and one S3 key can then serve several environments.

  • Both placeholders are required, each as a whole path segment. A template without {namespace} or {instance}, with a placeholder inside a segment (/{namespace}-{instance} renders the same path for a-b/c and a/b-c), with an unknown placeholder, or with ./.. segments would put several instances into one path. The operator refuses the central target in that case (no S3 repository, no bundle, a BackupTargetRefused event) instead of guessing.
  • The prefix applies to the central bucket only. An instance with its own bucket keeps its own layout, including its own s3.pathPrefix. On the central bucket a tenant's s3.pathPrefix is ignored (with one warning), with or without a central prefix: a tenant never chooses its path in the shared bucket. On the central bucket the operator owns the layout, whatever the tenant names. A spec bucket with the central bucket's name is the central target, whatever endpoint or credentials it adds, and any target written with the central credentials (no credentialsSecret and no credentialsFrom.secretRef in the spec) ignores s3.pathPrefix and refuses mode: replace. Only a tenant with its own credentials and its own bucket keeps its s3.pathPrefix.
  • Limit: this does not protect against a tenant that reads the central key out of the <instance>-pgbackrest-s3 Secret in its own namespace and uses it directly; per-tenant scoped keys or a gateway would be needed for that. A bucket named without credentials falls back to the central key, so scope the central key to the central bucket on the provider side.
  • An existing repository never moves. The base an instance's repository was set up under is kept in its backup record in the operator's namespace and wins over the setting. Changing the prefix later applies to repositories set up afterwards; the operator logs one warning per instance it keeps.

Per-instance encryption pass

By default (BACKUP_DB_CIPHER_DERIVATION unset or none) every instance that uses the central key is encrypted with that key itself, and the key is rendered into each instance's <instance>-pgbackrest-s3 Secret. Anyone who can read one of those Secrets can decrypt every instance's backups in the shared bucket.

With backup.dbDefaultS3.cipherDerivation: hmac-sha256-v1 (env BACKUP_DB_CIPHER_DERIVATION) the operator derives one pass per base prefix from the central key:

pass = lowercase hex( HMAC-SHA256( key = central key, message = "nextcloud-backup/v1:" + <base prefix> ) )

for example message = "nextcloud-backup/v1:/staging/tenants/nc-x/nextcloud". The same central key therefore gives a different pass per environment and per path. A repository you configure by hand (for example a shared database under /<env>/shared/<cluster>) can use the same formula with its own base prefix.

An instance with its own bucket that still uses the central key derives in a separate domain that also binds its bucket, so its input can never equal any central-bucket instance's:

pass = lowercase hex( HMAC-SHA256( key = central key, message = "nextcloud-backup/v1-instance:" + <bucket> + ":" + <base prefix> ) )

For the commands below, set BASE_PREFIX to <bucket>:<base prefix> and replace nextcloud-backup/v1: with nextcloud-backup/v1-instance: for such an instance. Naming the central bucket itself in an instance's spec does not make it an own bucket: the operator treats it as the central target in every respect.

A trailing newline on the central key is not part of the HMAC key. The derived pass is used for both halves: the pgBackRest repo2-cipher-pass and the configuration bundle, which the operator encrypts itself, in its own namespace. The central key never leaves the operator's namespace: an instance on hmac-sha256-v1 holds only its derived pass in <instance>-pgbackrest-s3. A key an instance names itself (encryption.keyFrom) is always used as it is, never derived.

An existing repository keeps its pass. pgBackRest cannot read a repository whose cipher pass changed, so switching the setting never changes the pass of an instance whose S3 repository already exists: the scheme is kept in the instance's backup record, next to the base prefix, and wins over the setting in both directions. The operator logs one warning per instance whose scheme it keeps. Turning derivation on therefore applies to instances that get their S3 repository afterwards; moving an existing instance to the derived pass means a new repository, the same procedure as a key rotation. The central key is written into a tenant's Secret only for an instance whose record says none.

To find the scheme and base prefix of an instance, read its record (authoritative) or the informational copies on the instance:

kubectl -n nextcloud-operator-system get configmap \
  -l app.kubernetes.io/component=backup-record \
  -o jsonpath='{range .items[*]}{.data.namespace}/{.data.name} {.data.scheme} {.data.basePrefix}{"\n"}{end}'
kubectl -n <namespace> get nci <instance> \
  -o jsonpath='{.status.backupCipherScheme} {.status.backupBasePrefix}{"\n"}'

Empty or none: the pass is the central key (cipher.key from step 1 above). For hmac-sha256-v1, derive the instance's pass from the central key and the base prefix with stock tools. Both commands below expect the central key in master.key and the base prefix in BASE_PREFIX, and write the instance's pass to cipher.key, which openssl enc -d -pass file:cipher.key and pgBackRest's repo2-cipher-pass then use:

kubectl -n nextcloud-operator-system get secret db-backup-cipher \
  -o jsonpath='{.data.cipher-pass}' | base64 -d > master.key
chmod 600 master.key
BASE_PREFIX=/staging/tenants/nc-x/nextcloud     # the record's basePrefix

With openssl:

printf '%s' "nextcloud-backup/v1:${BASE_PREFIX}" \
  | openssl dgst -sha256 -hmac "$(cat master.key)" \
  | sed 's/^.*= //' > cipher.key

With Python (the key stays off the command line):

MASTER="$(cat master.key)" python3 -c 'import hashlib, hmac, os, sys; print(hmac.new(os.environ["MASTER"].encode(), ("nextcloud-backup/v1:" + sys.argv[1]).encode(), hashlib.sha256).hexdigest())' "$BASE_PREFIX" > cipher.key

A database configured by hand in the same bucket (for example a shared PostgreSQL cluster that this operator does not manage) uses the same formula with its own base prefix, /<env>/shared/<cluster>:

BASE_PREFIX=/staging/shared/pg-main
# then run one of the two commands above; cipher.key holds that cluster's pass

and in that cluster's pgBackRest configuration:

[global]
repo2-path=/staging/shared/pg-main/db
repo2-cipher-type=aes-256-cbc
repo2-cipher-pass=<contents of cipher.key>

Put hand-configured repositories under a segment the central prefix never renders (here shared next to the operator's tenants), so they can never collide with an instance's base.

openssl dgst -hmac takes the key as a command-line argument, which other users of the machine can see in the process list; run it on a single-user workstation, or use the Python form. The test suite runs both commands as written here and compares their output with the operator's own derivation.

Backup records

How an instance's S3 repository was set up (its cipher scheme and base prefix) decides which pass goes into its <instance>-pgbackrest-s3 Secret and where its repo2 points. Nothing an instance's tenant can write decides it: not the annotations on that Secret, not the NextcloudInstance spec or status, not the PerconaPGCluster. It is kept in one ConfigMap per instance in the operator's namespace:

apiVersion: v1
kind: ConfigMap
metadata:
  name: nc-backup-record-<first 24 hex of sha256("<namespace>/<name>")>
  namespace: nextcloud-operator-system
  labels:
    app.kubernetes.io/managed-by: nextcloud-operator
    app.kubernetes.io/component: backup-record
data:
  namespace: <namespace>
  name: <instance>
  scheme: hmac-sha256-v1        # or none
  basePrefix: /staging/tenants/<namespace>/<instance>
  derivationDomain: "nextcloud-backup/v1:"   # own bucket: "nextcloud-backup/v1-instance:<bucket>:"; empty for none
  createdAt: "2026-10-26T01:00:00Z"
  • The operator writes it once, when it first sets up the S3 repository of an instance while cipherDerivation or pathPrefix is configured, from those settings and the instance's own namespace and name. It never changes or deletes it: the repository stays in the bucket after the instance is deleted, and an instance recreated under the same name uses the same path.
  • A record decides even after both settings are removed again.
  • No record, but the repository or its Secret already exists (an instance set up before 0.26.2, or before either setting was configured): the operator holds. It writes no Secret, does not change the cluster, and logs a warning with the reason. It never guesses none. To release the hold, create the record yourself with what the repository really uses. For a repository from before 0.26.2 that is the central key and the 0.26.1 layout:
NS=<namespace>; INST=<instance>
NAME=nc-backup-record-$(printf '%s' "$NS/$INST" | sha256sum | cut -c1-24)
kubectl -n nextcloud-operator-system create configmap "$NAME" \
  --from-literal=namespace="$NS" --from-literal=name="$INST" \
  --from-literal=scheme=none --from-literal=basePrefix="/$NS/$INST/backups"
kubectl -n nextcloud-operator-system label configmap "$NAME" \
  app.kubernetes.io/managed-by=nextcloud-operator app.kubernetes.io/component=backup-record
  • A record with an unknown scheme, a malformed base prefix, or another instance's namespace/name is never used; the operator holds. So does an unknown cipherDerivation value.
  • Without either setting and without a record, the operator behaves as 0.26.1: the central key verbatim in every instance's Secret, the /<namespace>/<instance>/backups layout, and no record.

Rotating either central Secret re-syncs every instance namespace on the next reconcile tick (the 30-second instance timer), because the derived <instance>-pgbackrest-s3 Secret is compared by content hash — only instances whose rendered s3.conf actually changed are rewritten. During that cutover window some instances still hold the old values, so keep the old S3 key valid until the fleet has converged; see Rotating the central credentials for the convergence check.