Business tech · Intermediate · 15 min
Self-host n8n with Docker Compose and PostgreSQL
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Docker Compose 5 · n8n 2.49.7 · PostgreSQL 18
You will run n8n 2.49 and PostgreSQL 18 from one compose.yaml on your own server, with secrets in a private env file, HTTPS through Caddy and an owner account ready for your first workflow.
On this page
n8n is a workflow automation tool: you connect a trigger (a form, a schedule, an incoming email) to a chain of steps, and it runs them for you. You can pay for n8n's cloud service, or run the same software on a server you control, where your data and your credentials for other services stay with you.
This tutorial sets n8n up for Ember Studio, a fictional seven-person design agency with staff in Lagos and Nairobi. By the end, the team opens https://n8n.emberstudio.example in a browser, sees the n8n editor behind a valid certificate, and signs in with an owner account. Under the hood, two containers run from one compose.yaml: n8n itself, pinned to release 2.49.7, and PostgreSQL 18, which stores workflows, run history and encrypted credentials. Caddy on the host terminates HTTPS and passes requests to n8n.
If Docker Compose is new to you, read /tutorials/docker-compose-app-with-postgres first. This tutorial uses the same ideas (a private .env file, named volumes, a health check before the app starts) and does not explain them again in depth.
Step 1 · Check the licence covers your use
n8n is not open source in the OSI sense. Most of its code is under the Sustainable Use License, version 1.0, published in the LICENSE.md file of the n8n repository. Read it before you build anything that depends on it. The short version, in plain terms:
- You may use and modify n8n for your own internal business purposes, or for non-commercial or personal use. Automating Ember Studio's own enquiries, invoices and onboarding is internal business use.
- You may give copies to others only free of charge and for non-commercial purposes.
- You may not, under this licence, sell n8n to others as a hosted service, for example by running instances for clients and charging for them. That needs a separate agreement with n8n.
- Files with
.ee.in their name or.eein their folder name are enterprise features. They need an n8n Enterprise licence, even on your own server. The free self-hosted edition (the Community Edition) leaves them switched off.
This is a reading of the licence text, not legal advice. If your plan sits near the line, such as building automations for paying clients on a server you run for them, ask n8n or a lawyer before you start.
Check it worked
Write one sentence describing what you will use n8n for and who pays for it, and put it in your project notes. For Ember Studio it reads: "Internal automations for Ember Studio staff; no client pays for access to n8n." If your sentence says a client pays for access to n8n itself, stop and get a licence answer first.
Step 2 · Prepare a project folder on the server
Sign in to the server and confirm that the Compose plugin is installed:
docker compose versionThe output starts with Docker Compose version v. If the command is not found, install Docker Engine from Docker's apt repository as in /tutorials/install-docker-engine-on-ubuntu-26-04, which includes the plugin.
Create a folder for the stack. Everything n8n needs to start lives here, apart from the data, which lives in Docker volumes:
mkdir -p ~/n8n-compose
cd ~/n8n-composeCheck it worked
pwd prints a path ending in /n8n-compose, and ls -A prints nothing because the folder is empty. Run every command from here on in this folder.
Step 3 · Create the private env file
Two values must never appear in compose.yaml or in Git: the database password and N8N_ENCRYPTION_KEY. n8n uses the encryption key to encrypt every credential you save in it (API keys, OAuth tokens, SMTP passwords) before writing them to PostgreSQL. If you lose the key, those credentials cannot be decrypted and every connection has to be set up again. If you leave the key unset, n8n generates one on first start and keeps it only inside its data volume, which is easy to lose in a rebuild. Generating it yourself means you hold a copy.
Create the file empty and private first, then add the values to it, so it is never readable by other users on the server. Replace n8n.emberstudio.example with your own subdomain on the first line before you run this:
N8N_DOMAIN=n8n.emberstudio.example # replace this with your subdomain
install -m 600 /dev/null .env
{
echo "N8N_DOMAIN=$N8N_DOMAIN"
echo "POSTGRES_PASSWORD=$(openssl rand -hex 24)"
echo "N8N_ENCRYPTION_KEY=$(openssl rand -hex 32)"
} >> .envThe two secrets come from openssl rand, so you never type them and they never land in your shell history.
Now copy the encryption key into your team's password manager (see /tutorials/roll-out-a-password-manager-to-your-team). Make sure nobody can see your screen (do not do this during a screen share), then print it once, copy it, and clear the screen:
grep '^N8N_ENCRYPTION_KEY=' .envCheck it worked
ls -l .env
cut -d= -f1 .envThe listing starts with -rw-------, which means only your user can read the file. The second command prints the three variable names, N8N_DOMAIN, POSTGRES_PASSWORD and N8N_ENCRYPTION_KEY, without their values. Your password manager has a new entry holding the encryption key.
Step 4 · Write compose.yaml
Create the compose file. It describes two services, two named volumes and the settings n8n needs to work behind a reverse proxy:
cat > compose.yaml <<'YAML'
name: n8n
services:
postgres:
image: postgres:18
restart: unless-stopped
environment:
POSTGRES_USER: n8n
POSTGRES_DB: n8n
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
volumes:
- db_data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U n8n -d n8n"]
interval: 5s
timeout: 5s
retries: 10
start_period: 30s
n8n:
image: n8nio/n8n:2.49.7
restart: unless-stopped
ports:
- "127.0.0.1:5678:5678"
environment:
DB_TYPE: postgresdb
DB_POSTGRESDB_HOST: postgres
DB_POSTGRESDB_PORT: "5432"
DB_POSTGRESDB_DATABASE: n8n
DB_POSTGRESDB_USER: n8n
DB_POSTGRESDB_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY:?set N8N_ENCRYPTION_KEY in .env}
N8N_HOST: ${N8N_DOMAIN:?set N8N_DOMAIN in .env}
N8N_PORT: "5678"
N8N_PROTOCOL: https
N8N_EDITOR_BASE_URL: https://${N8N_DOMAIN}/
N8N_WEBHOOK_URL: https://${N8N_DOMAIN}/
N8N_PROXY_HOPS: "1"
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
GENERIC_TIMEZONE: Africa/Lagos
TZ: Africa/Lagos
volumes:
- n8n_data:/home/node/.n8n
depends_on:
postgres:
condition: service_healthy
volumes:
db_data:
n8n_data:
YAMLThe choices that matter:
n8nio/n8n:2.49.7pins an exact release. A baren8nio/n8nmeanslatest, which can jump a major version the next time the image is pulled. You upgrade on purpose, after a backup, as in/tutorials/back-up-and-update-a-self-hosted-n8n.- The database has no
portsentry, so only n8n can reach it, over the private network Compose creates. n8n finds it by the service namepostgres. 127.0.0.1:5678:5678publishes n8n on the server's loopback address only. Ports that Docker publishes on all addresses skipufwrules, so binding to127.0.0.1is what keeps port 5678 off the internet. Caddy, on the same server, is the only way in.n8n_datais mounted at/home/node/.n8n. With PostgreSQL holding the workflows you still keep this volume: it holds n8n's settings file, which includes the encryption key in use.N8N_HOST,N8N_PROTOCOLandN8N_EDITOR_BASE_URLtell n8n its public address, so links and emails it sends usehttps://and your domain rather thanlocalhost:5678. n8n still serves plain HTTP inside; Caddy handles TLS.N8N_WEBHOOK_URLis the address n8n shows for webhook triggers. Older guides call itWEBHOOK_URL; that name is deprecated from n8n 2.35.0 and logs a warning.N8N_PROXY_HOPS: "1"tells n8n there is one proxy in front of it, so it trusts theX-Forwarded-*headers from Caddy and records the visitor's real IP address.N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"makes n8n set its settings file inside/home/node/.n8nto0600, readable only by the user n8n runs as. That file holds the encryption key, so other accounts in the container cannot read it.GENERIC_TIMEZONEsets the time zone that Schedule triggers use, andTZsets the container clock. Ember Studio picksAfrica/Lagos(West Africa Time, UTC+1), where most of the team works. Its Nairobi staff are on UTC+3, so a workflow set for 09:00 runs at 11:00 Nairobi time. Pick the zone of the people the schedules are for, using a name from the IANA list such asAfrica/NairobiorEurope/London.
Ask Compose to read the file, fill in the variables from .env and report any mistake:
docker compose config --quiet && echo "compose.yaml is valid"Plain docker compose config prints the whole file with the secrets filled in, so do not paste its output anywhere.
Check it worked
The command prints compose.yaml is valid. Then list what Compose will create:
docker compose config --services
docker compose config --volumesThe first command prints postgres and n8n, the second db_data and n8n_data. If you see required variable ... is missing a value, you are not in ~/n8n-compose or a line in .env is missing.
Step 5 · Start n8n and PostgreSQL
Pull the images and start both containers in the background. --wait returns once the database is healthy and n8n is running:
docker compose up -d --waitThe first run downloads both images, which takes a minute or two on a typical server connection. On its first start n8n creates its tables in PostgreSQL, so give it up to a minute more before the next check.
Check it worked
Ask n8n whether it is up, then whether it is ready:
curl -s http://127.0.0.1:5678/healthz
curl -s http://127.0.0.1:5678/healthz/readinessBoth print {"status":"ok"}. The first only says the web server answers. The second answers ok only when n8n is connected to PostgreSQL and has finished setting up its tables; until then it returns {"status":"error"} with status 503. docker compose ps lists n8n-postgres-1 as healthy and n8n-n8n-1 as running. If n8n keeps restarting, docker compose logs n8n --tail 50 usually names the cause, often a wrong database password after you edited .env once the volume already existed.
Step 6 · Put n8n behind HTTPS with Caddy
n8n now answers on 127.0.0.1:5678, which nobody outside the server can reach. Caddy, installed as in /tutorials/automatic-https-with-caddy-2, gets a certificate for your subdomain and forwards requests to n8n.
Open /etc/caddy/Caddyfile with sudo nano /etc/caddy/Caddyfile and add this site block at the end, with your own subdomain in place of n8n.emberstudio.example. Leave any other site blocks in the file as they are:
n8n.emberstudio.example {
reverse_proxy 127.0.0.1:5678
}Then check the file and reload Caddy:
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
sudo systemctl reload caddyThat one line is enough because Caddy's reverse_proxy already sends the X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host headers n8n reads, and passes WebSocket connections through, which the n8n editor uses for live updates. If you use Nginx instead, follow /tutorials/nginx-reverse-proxy-for-a-node-app and /tutorials/free-https-with-lets-encrypt-and-nginx, and add the WebSocket upgrade headers from /tutorials/proxy-websockets-through-nginx; without them the editor loads but stops updating as workflows run.
Check it worked
From your laptop, not the server:
curl -s https://n8n.emberstudio.example/healthzIt prints {"status":"ok"} with no certificate warning. If curl reports a certificate error, Caddy could not get a certificate yet: check that the A record points at this server and that ports 80 and 443 are open, then read sudo journalctl -u caddy --since "10 minutes ago".
Step 7 · Create the owner account
Open https://n8n.emberstudio.example in a browser. A fresh n8n shows a setup form instead of a sign-in page. The first person to fill it in becomes the instance owner, with full control, so do this straight after the previous step rather than leaving the form open to anyone who finds the address.
Enter an email address you will keep (use a shared admin address such as it@ rather than one person's inbox if staff change), a first and last name, and a password of 8 to 64 characters with at least one number and one capital letter. Generate it in your password manager and save it there, next to the encryption key.
n8n may then offer a short questionnaire and a free licence key for some extra Community Edition features by email. Both are optional.
Check it worked
You land on the n8n overview page, signed in, with an empty list of workflows. To confirm the account is stored in PostgreSQL, not in a local file inside the container, ask the database:
docker compose exec postgres psql -U n8n -d n8n -c 'SELECT email FROM "user";'The result lists the owner email you entered. Sign out and back in once to make sure the password in your password manager is the right one.
Next steps
- Build your first automation on this instance in /tutorials/build-your-first-n8n-workflow-with-a-webhook, which uses the webhook address you set with
N8N_WEBHOOK_URL. - Before you rely on it, set up backups of the database, the
.envfile and the encryption key, and practise an upgrade to a newer pinned release, in /tutorials/back-up-and-update-a-self-hosted-n8n. - For more on how Compose handles the database, volumes and health checks used here, see /tutorials/docker-compose-app-with-postgres.
- Close every other port on the server with /tutorials/set-up-ufw-firewall-ubuntu-26-04, keeping 22, 80 and 443 open.
Related tutorials
- Build your first n8n workflow with a webhook triggerYou will have a published n8n workflow that takes a website enquiry by POST, checks a secret header, rejects enquiries without an email address and answers with JSON.
- Back up and update a self-hosted n8nYou will back up a self-hosted n8n 2.49 instance (workflow and credential exports, a database dump and the encryption key), prove the backup by restoring it on a fresh instance, then update the pinned image tag with a rollback plan ready.
- Write a privacy notice for a small business websiteYou will turn your data inventory into a plain-language privacy notice that names every tool you use, meets the transparency lists in the GDPR, Nigeria's Data Protection Act and South Africa's POPIA, and is linked from every form on your site.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials