n8n Docker Compose: persistent data, HTTPS and recovery
An n8n Docker Compose setup is straightforward to start, but harder to recover correctly. A running editor doesn’t prove your workflows, credentials, and webhook addresses will survive a host failure. This guide builds a single-server n8n installation with PostgreSQL, persistent Docker volumes, automatic HTTPS and a repeatable backup and restore procedure.
The configuration uses pinned container versions and separates three concerns: the application, its database and the public reverse proxy. The recovery exercise deliberately targets an empty staging deployment rather than risking production data. It covers one n8n instance; Redis, additional workers and queue mode belong in a separate scaling design.
Use three services, not a public database port
For a small production installation, the useful starting point is n8n, PostgreSQL and Caddy. PostgreSQL holds workflows, credential records, users and execution metadata. The n8n data volume retains application settings, the configuration directory and any files kept there. Caddy handles certificates and forwards HTTPS requests internally to port 5678.
| Component | Pinned image | What survives a replacement |
|---|---|---|
| n8n | n8nio/n8n:2.47.7 | n8n_data volume and a separately saved encryption key |
| PostgreSQL | postgres:17.11-alpine3.23 | postgres_data volume plus logical database backups |
| Caddy | caddy:2.11.9-alpine | Certificate storage in caddy_data; certificates can also be reissued |
The versions are fixed intentionally. latest introduces an unreviewed upgrade when you next pull images. PostgreSQL 17 also keeps this example on the established data-directory layout, avoiding an accidental major-version migration.
1. Create the Compose deployment
On a Linux host with Docker Engine and the Compose plugin installed, create a working directory containing compose.yaml, .env and Caddyfile. Point an A record, and an AAAA record if you use IPv6, at the host. Allow inbound ports 80 and 443; they must not already belong to another web server.
Use this compose.yaml:
services:
postgres:
image: postgres:17.11-alpine3.23
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:?Set POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER:?Set POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
interval: 10s
timeout: 5s
retries: 10
n8n:
image: n8nio/n8n:2.47.7
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
environment:
DB_TYPE: postgresdb
DB_POSTGRESDB_HOST: postgres
DB_POSTGRESDB_PORT: 5432
DB_POSTGRESDB_DATABASE: ${POSTGRES_DB:?Set POSTGRES_DB}
DB_POSTGRESDB_USER: ${POSTGRES_USER:?Set POSTGRES_USER}
DB_POSTGRESDB_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY:?Set N8N_ENCRYPTION_KEY}
N8N_HOST: ${N8N_DOMAIN:?Set N8N_DOMAIN}
N8N_PORT: 5678
N8N_PROTOCOL: https
N8N_EDITOR_BASE_URL: https://${N8N_DOMAIN:?Set N8N_DOMAIN}/
N8N_WEBHOOK_URL: https://${N8N_DOMAIN:?Set N8N_DOMAIN}/
N8N_PROXY_HOPS: 1
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
GENERIC_TIMEZONE: ${GENERIC_TIMEZONE:-Europe/London}
TZ: ${GENERIC_TIMEZONE:-Europe/London}
volumes:
- n8n_data:/home/node/.n8n
caddy:
image: caddy:2.11.9-alpine
restart: unless-stopped
depends_on:
- n8n
environment:
N8N_DOMAIN: ${N8N_DOMAIN:?Set N8N_DOMAIN}
ports:
- "80:80"
- "443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- caddy_config:/config
volumes:
postgres_data:
n8n_data:
caddy_data:
caddy_config:
Notice the absent ports entries for n8n and PostgreSQL. They remain reachable inside the Docker Compose network, not directly from the internet. Only Caddy publishes ports to the host. depends_on with a PostgreSQL health check reduces database-startup races, but does not replace application monitoring.
2. Set the hostname and preserve the encryption key
Copy the following template to .env, then replace both secret placeholders with different values generated using openssl rand -hex 32. Do not put real secrets into a Git repository. Set chmod 600 .env and retain an encrypted, off-host copy.
# Set a unique project name for each separate deployment.
COMPOSE_PROJECT_NAME=n8n-prod
N8N_DOMAIN=n8n.example.com
GENERIC_TIMEZONE=Europe/London
POSTGRES_DB=n8n
POSTGRES_USER=n8n
POSTGRES_PASSWORD=REPLACE_WITH_OPENSSL_RAND_HEX_32_OUTPUT
N8N_ENCRYPTION_KEY=REPLACE_WITH_DIFFERENT_OPENSSL_RAND_HEX_32_OUTPUT
Do not rotate N8N_ENCRYPTION_KEY casually. Credentials are stored encrypted in the database, and restoring the database under a different key makes existing credentials unreadable. The saved .n8n folder matters even when PostgreSQL is external. A workflow-only JSON export does not recreate the entire installation.
Also treat the PostgreSQL password as an installation secret. Replacing it in .env after the database has been initialised does not automatically update the password stored inside PostgreSQL.
3. Enable HTTPS and correct public webhook URLs
Use this Caddyfile. Caddy obtains and renews HTTPS certificates for the configured domain, provided DNS and public network access are correct.
{$N8N_DOMAIN} {
encode zstd gzip
reverse_proxy n8n:5678
}
The important n8n settings are N8N_EDITOR_BASE_URL, N8N_WEBHOOK_URL and N8N_PROXY_HOPS=1. The first tells the editor its public origin; the second gives external services an HTTPS webhook address; the third reflects Caddy as the single trusted proxy hop. Older guides use WEBHOOK_URL, which has been superseded in the pinned n8n version.
If Cloudflare or another proxy sits in front of Caddy, review the chain of forwarded headers and TLS settings rather than blindly retaining a one-hop assumption. Do not enable an insecure or flexible HTTPS arrangement to make certificate errors disappear. An authentication gateway also needs to allow the specific public webhook paths you intend to receive.
4. Start n8n and check something more useful than container uptime
Validate the rendered configuration before creating containers:
cp .env.example .env
chmod 600 .env
# Edit .env; generate a separate random value for each secret.
docker compose config -q
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --tail=80 n8n caddy
Visit the HTTPS hostname and complete owner account setup. Create a manual-trigger workflow with a unique recovery marker in its name, add a harmless test credential and run it once. Save the workflow name, the expected credential and an execution identifier if history retention is enabled. These are recovery assertions, not decorative smoke tests.
Then add a Webhook trigger, activate the workflow and inspect its production URL. It should begin with https://your-domain/webhook/, not http://localhost:5678/. Test the endpoint from outside the server, and check that requests arrive at the intended workflow. The test URL and production URL are different paths with different activation behaviour.
5. Back up the database and application volume as a single recovery set
The most common false sense of security comes from backing up workflows while forgetting the encryption key. Another failure is copying only the PostgreSQL Docker volume while n8n is still writing and assuming it is a consistent database backup. For this small setup, accept a short maintenance window and stop the application before capturing both stores.
The accompanying editor bundle includes scripts/backup.sh. Its essential sequence is:
docker compose stop n8n
mkdir -p backups/drill-01
docker compose exec -T postgres sh -c \
'exec pg_dump -Fc --no-owner --no-acl -U "$POSTGRES_USER" -d "$POSTGRES_DB"' \
> backups/drill-01/n8n.pgcustom
docker run --rm \
-v n8n-prod_n8n_data:/data:ro \
-v "$PWD/backups/drill-01:/backup" \
alpine:3.23.6 tar -czf /backup/n8n-data.tar.gz -C /data .
cp -p .env compose.yaml Caddyfile backups/drill-01/
docker compose start n8n
The n8n-prod_n8n_data volume name assumes the example COMPOSE_PROJECT_NAME. Verify it with docker volume ls before running this manually. The packaged script checks the volume and restarts the application if an intermediate step fails. The -T flag is essential when redirecting a binary PostgreSQL archive because an allocated terminal can corrupt the byte stream.
Keep a checksum manifest, encrypt the archive before uploading it elsewhere and test both archives for readability. Copying a backup to the same VPS disk is useful for small mistakes, but offers no protection against losing the host. If you have separate file mounts, custom extensions or external binary storage, extend the backup scope; this sample captures the data locations it actually configures.
6. Prove recovery on a separate, empty deployment
A successful pg_dump command is not a successful restore. Copy the backup set to a separate machine, retain the same encryption key and database credentials, but change the Compose project name and staging hostname. Start with empty application and database volumes. Never run this exercise against production volumes, and never use docker compose down -v on a live installation.
The bundle’s scripts/restore-test.sh checks archive checksums, refuses an existing target volume, restores the n8n directory and imports PostgreSQL with pg_restore --exit-on-error. It intentionally leaves n8n stopped at the end:
# On the separate staging host, after setting its .env:
bash scripts/restore-test.sh /path/to/backups/drill-01
# First isolate the staging server's outbound connections.
# Only then start the recovered application and proxy.
docker compose up -d n8n caddy
docker compose ps
This isolation step prevents cloned scheduled workflows from emailing customers, charging cards or calling third-party APIs while you inspect the restore. Configure a separate DNS name for staging; Caddy needs the correct hostname to establish HTTPS. Once running, compare the recovered workflow with the original, confirm that historical execution records still exist where retained, and test a credential against a safe endpoint you control. A credential appearing in a list is not proof that its encrypted contents can be decrypted and used.
Verification status: The published example is a reference configuration with syntax-checked YAML and shell scripts. A live Docker deployment and full restore have not been executed as part of this article. The following acceptance criteria describe the exercise needed before it can be called recovery-tested.
Recovery acceptance checks: what counts as a pass?
| Check | Pass condition | What a failure suggests |
|---|---|---|
| Workflow identity | Recovery marker and node settings match the source | Wrong database, old snapshot or incomplete export |
| Stored credential | A safe credential test authenticates successfully | Incorrect or missing encryption key |
| Execution history | Pre-backup execution is present, unless pruned earlier | Wrong database or retention misunderstanding |
| HTTPS and webhook | External request reaches the staging production webhook URL | DNS, proxy headers, hostname or activation error |
| Restart | Workflow and credentials survive docker compose up -d after a normal stop | Missing volume mount or wrong project name |
Record the backup timestamp, image tags, archive checksums, test results and time taken to recover. Those details let you estimate recovery time without inventing a guarantee. A backup policy should specify how much recent work you can afford to lose: a nightly archive cannot recover changes made after that archive.
See more of our reporting in Google Top Stories, AI Overviews and AI Mode.
Five faults that look like application failures
- Credentials exist but do not work: compare
N8N_ENCRYPTION_KEYwith the source; do not generate a fresh key during restoration. - Editor loads but webhook URLs use localhost: confirm
N8N_WEBHOOK_URL, the public hostname and the proxy hop count. - Database has disappeared after a rebuild: check
docker volume lsand the Compose project name. Renaming the project can create an apparently blank deployment with new volumes. - HTTPS will not issue: check DNS, inbound 80/443, whether an existing process owns those ports and any upstream proxy configuration.
- Everything restores except uploaded binary files: inspect the storage mode and any paths outside the mounted
.n8nfolder. They require their own backup.
For a related example of protecting persistent directories and network boundaries in a different self-hosted AI service, see our OpenClaw Docker setup guide. If your eventual n8n workflows move data into spreadsheets, our spreadsheet automation comparison helps decide whether a purpose-built integration layer is warranted.
Operating this setup without creating the next outage
Take a fresh paired backup before every image change. Update the exact n8n tag deliberately, inspect migration notes, and try the upgrade against a restored staging copy first. Avoid changing PostgreSQL major versions as part of a routine n8n update. Keep the editor behind strong account authentication and, where possible, an additional access policy, while allowing only the webhook endpoints that must be public.
Self-hosting saves some subscription fees at the cost of server patches, backups, incident response and workflow monitoring. The single-server arrangement is reasonable when you can tolerate its downtime and recovery window. It is not high availability, and scaling the number of workers without first fixing your recovery process simply creates more state to account for.
Use the official n8n Docker Compose installation guide to cross-check platform requirements and configuration changes before deployment.
Deployment sign-off checklist
- The Compose project and all image tags are explicitly set.
- Only ports 80 and 443 are exposed; PostgreSQL and n8n are internal.
- The hostname, HTTPS certificate and public webhook URL are correct.
- The application volume, PostgreSQL dump, environment file and encryption key are backed up together.
- A staging restore passes the credential, workflow, history and webhook checks without running production side effects.
- Backups are encrypted off-site, and retention and restore responsibility are assigned.
Practical rule: do not call an n8n installation recoverable until a second host has restored its database and application state and successfully used a preserved credential. A green container status is only the beginning of that test.


