eco Beginner Tutorial/How-to

Installing ZITADEL on a VPS: Self-Hosted IAM, PostgreSQL, SSL, SMTP, and Backups

We earn commissions when you shop through the links below.

calendar_month Nov 02, 2026 schedule 19 min read visibility 505 views
Установка ZITADEL на VPS: self-hosted IAM, PostgreSQL, SSL, SMTP и резервное копирование
dns No server for this guide yet? Vultr, DigitalOcean, Contabo

Installing ZITADEL on a VPS: self-hosted IAM, PostgreSQL, SSL, SMTP, and backups

TL;DR

ZITADEL can be deployed on your own VPS as a unified identity and access management service: with PostgreSQL, HTTPS, SMTP, MFA, organizations, projects, and OAuth 2.0/OpenID Connect. This guide uses Docker Compose, PostgreSQL 16, Caddy for automatic TLS, and restic for encrypted backups.

  • For a small production installation, 2 vCPU, 4 GB RAM, and an SSD of at least 40 GB are sufficient.
  • ZITADEL runs in Docker, while PostgreSQL stores users, organizations, projects, and settings.
  • The domain points to the VPS, and Caddy automatically obtains a Let’s Encrypt certificate.
  • SMTP is required for invitations, password recovery, notifications, and MFA codes.
  • Backups include PostgreSQL, the Compose configuration, secrets, and the ZITADEL master key.

1. TL;DR

ZITADEL is a self-hosted IAM platform for centralized authentication of users, services, and administrators. It supports OpenID Connect, OAuth 2.0, SAML, WebAuthn, MFA, organizations, and a project-based access model. In this guide, the service is hosted on Ubuntu Server 24.04 LTS, PostgreSQL runs in a separate container, and external access passes through Caddy.

The commands are intended for a clean server with a public IPv4 address and the auth.example.com domain. Before running them, replace this domain, passwords, email address, and S3 values with your own.

  • System: Ubuntu Server 24.04 LTS, Docker Engine 28.x or newer, Docker Compose v2.
  • Application: ZITADEL 4.x; the image is pinned to a specific tag rather than latest.
  • Database: PostgreSQL 16.x in Docker Compose.
  • Proxy: Caddy 2.10.x with an automatic Let’s Encrypt certificate.
  • Backup: pg_dump and restic to S3-compatible object storage.

2. Contents

The article is structured as a practical scenario: first the server is selected, then basic system hardening is performed, after which the containers are launched and the domain, TLS, SMTP, and backups are configured.

  1. Task and architecture review.
  2. VPS or dedicated server resource calculation.
  3. Creating a separate administrator and configuring SSH.
  4. Installing Docker and preparing directories.
  5. Launching PostgreSQL and ZITADEL.
  6. Configuring Caddy, HTTPS, and SMTP.
  7. Checking OAuth/OIDC, healthcheck, and logs.
  8. Automated backups, restoration, and updates.

3. What we are configuring and why

The role of ZITADEL in the infrastructure

Without IAM, each web service usually stores its own users, passwords, roles, and sessions. This results in multiple account databases, different MFA policies, and complicated employee access removal. ZITADEL separates authentication into a dedicated service: the application redirects the user to the login page, receives a signed token, and checks the user's permissions.

The practical result is single sign-on for internal panels, SaaS applications, Mattermost, Git services, VPN portals, and custom APIs. Standard OpenID Connect is used for integrations, so the application does not need to know the user's password or implement access recovery itself.

Architecture of this guide

Component Purpose Public access
Caddy HTTPS, reverse proxy, automatic certificate renewal TCP 80 and 443
ZITADEL IAM, OIDC, OAuth 2.0, administrative interface Only through Caddy
PostgreSQL 16 Storing ZITADEL state Internal Docker network only
restic Encrypting and sending backups Outgoing connections to S3

What will be ready after completion

  • Administrative console address: https://auth.example.com/ui/console.
  • PostgreSQL with no publicly exposed port.
  • HTTPS with a valid certificate and automatic renewal.
  • SMTP for invitations and account recovery.
  • OIDC-compatible IAM for multiple applications.
  • Daily encrypted backup of the database and configuration.

Self-hosted or cloud-managed

Cloud IAM reduces operational workload: the provider is responsible for updates, redundancy, availability, and some security measures. This is convenient if IAM is not a critical infrastructure control or the team is not prepared to respond to outages independently.

Self-hosted ZITADEL on a VPS is suitable when control over data, predictable costs, a custom domain, and the ability to isolate IAM in a chosen jurisdiction are important. The downside is that the owner is responsible for patches, monitoring, secrets, SMTP, backups, and recovery. IAM cannot be considered reliable merely because the container is running: the recovery procedure must be tested regularly.

Limitations

ZITADEL does not replace LDAP for all legacy applications, although specific integration scenarios are possible. It is also not a secrets management system for servers. Database passwords, the master key, and restic keys should be stored separately from the source code and preferably in a secrets manager.

4. What VPS configuration is required for this task

Minimum configuration

For a test environment and a small team of a few dozen users, 2 vCPU, 4 GB RAM, and a 40 GB SSD are sufficient. A minimum of 2 GB RAM is possible, but when PostgreSQL, ZITADEL, Caddy, Docker, and the backup process run simultaneously, there is practically no spare capacity.

Scenario CPU RAM Disk Network
Testing 1–2 vCPU 2–4 GB 30–40 GB SSD 100 Mbps
Small production team 2–4 vCPU 4–8 GB 60–100 GB NVMe 100–1000 Mbps
Many organizations and applications 4–8 vCPU 8–16 GB 100+ GB NVMe 1 Gbps

For a typical installation, you can choose a VPS with these specifications: 2–4 vCPU, 4–8 GB RAM, at least 60 GB SSD/NVMe, a public IPv4 address, and the ability to open TCP 80 and 443. The disk must account for more than just the database: logs, Docker image updates, and temporary dump files can consume several gigabytes.

When a dedicated server is needed

A separate physical server is usually not required for a single ZITADEL instance. A dedicated server is justified if IAM runs alongside a large number of services, the database contains tens or hundreds of thousands of objects, guaranteed resources without neighboring tenants are required, or security policy prohibits virtualization on a shared host.

One dedicated server is also insufficient for high availability: if the disk or power fails, the service will still stop. Two independent nodes, PostgreSQL replication, an external load balancer, and tested recovery are more important. For most small installations, it is better to start with a VPS and store backups separately.

Location and network

Choose a region close to your users and applications. Distance affects the latency of OIDC redirects, console loading speed, and API response time. If applications are located in multiple regions, place IAM where most users are located, or use a CDN and a separate high-availability architecture.

A public IPv4 address, a correctly configured PTR record—preferably for the mail infrastructure—and the ability to configure DNS records are required. For Caddy, the domain must point to the VPS before the proxy is launched; otherwise, Let’s Encrypt certificate issuance will fail.

5. Server preparation

Logging in and updating Ubuntu

Connect to the server using the temporary user provided by the provider. All commands below are executed by a user with sudo privileges. The example uses Ubuntu 24.04 LTS with the amd64 or arm64 system architecture.

# Проверяем версию системы и обновляем пакеты
cat /etc/os-release
sudo apt update && sudo apt full-upgrade -y

# Устанавливаем базовые инструменты
sudo apt install -y ca-certificates curl gnupg lsb-release \
  git jq unzip vim ufw fail2ban unattended-upgrades

After updating the kernel, check whether a reboot is required. If the kernel or critical system libraries have changed, restart the server during an agreed maintenance window.

# Показываем, требуется ли перезагрузка
if [ -f /var/run/reboot-required ]; then echo "Требуется reboot"; fi

# После согласования окна обслуживания
sudo reboot

Separate user and SSH keys

Do not use root for routine work. Create an administrator, add a public key, and disable password authentication only after verifying the new login. Do not close the current SSH session until the new session has been confirmed.

# Создаём отдельного администратора
sudo adduser deploy
sudo usermod -aG sudo deploy

# Создаём каталог SSH и добавляем ваш публичный ключ
sudo install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
sudo nano /home/deploy/.ssh/authorized_keys
sudo chown deploy:deploy /home/deploy/.ssh/authorized_keys
sudo chmod 600 /home/deploy/.ssh/authorized_keys

Insert one line containing the ssh-ed25519 key into the authorized_keys file. After verifying the connection, modify the SSH configuration.

# Отключаем root-вход и пароли после проверки ключевого доступа
sudo tee /etc/ssh/sshd_config.d/10-hardening.conf > /dev/null <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 4
EOF

# Проверяем синтаксис и перечитываем конфигурацию SSH
sudo sshd -t && sudo systemctl reload ssh

Firewall and fail2ban

Open SSH, HTTP, and HTTPS. If SSH runs on a non-standard port, replace the value in the rule. Do not expose the PostgreSQL port externally: the containers will communicate through the internal Docker network.

# Разрешаем только необходимые входящие соединения
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp comment 'SSH'
sudo ufw allow 80/tcp comment 'HTTP for ACME'
sudo ufw allow 443/tcp comment 'HTTPS'
sudo ufw --force enable
sudo ufw status verbose

# Запускаем защиту от перебора SSH
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

Docker publishes ports through its own iptables/nftables rules. Therefore, PostgreSQL should not be published through Compose even when UFW is enabled. Check the list of listening ports after starting the services.

6. Software Installation — Step by Step

Installing Docker Engine and Compose

Use the official Docker repository rather than outdated packages from random scripts. In 2026, Docker Engine 28.x and Docker Compose v2 are sufficient for this guide. Installation should not be performed via an unverified curl script from an unknown source.

# Add the official Docker repository key
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
  sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg

# Add the Docker repository for the current Ubuntu release
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Engine, CLI, Buildx, and Compose plugin
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io \
  docker-buildx-plugin docker-compose-plugin

# Check versions and enable automatic startup
sudo docker version
sudo docker compose version
sudo systemctl enable --now docker

Adding a user to the docker group allows Docker to be run without sudo, but effectively grants root privileges. On a production server, you can keep using commands through sudo; this reduces the risk of accidentally launching a dangerous container from a regular shell session.

Creating Project Directories

# Create separate directories for configuration, data, and backups
sudo install -d -m 750 /opt/zitadel
sudo install -d -m 750 /opt/zitadel/caddy
sudo install -d -m 750 /opt/zitadel/postgres
sudo install -d -m 750 /opt/zitadel/backups
sudo chown -R deploy:deploy /opt/zitadel

# Change to the application directory
cd /opt/zitadel

The Compose configuration below uses PostgreSQL 16 and ZITADEL 4.x. Pin a specific verified image tag, for example ghcr.io/zitadel/zitadel:v4.0.0, if this tag is available in the official registry at the time of installation. Before deploying to production, check the current stable release and migration notes in the official ZITADEL documentation.

Preparing the Secrets File

Secrets must not be committed to Git, exposed in public logs, or included in commands saved in shell history. Create a .env file, restrict its permissions, and add it to Git exclusions. The master key must be stored in a separate secure location: without it, a restored ZITADEL database may be unusable.

# Generate random values and create a protected .env
cd /opt/zitadel
umask 077
POSTGRES_PASSWORD="$(openssl rand -base64 36 | tr -dc 'A-Za-z0-9' | head -c 32)"
MASTER_KEY="$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 32)"
RESTIC_PASSWORD="$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 40)"

cat > .env <<EOF
ZITADEL_DOMAIN=auth.example.com
ZITADEL_IMAGE=ghcr.io/zitadel/zitadel:v4.0.0
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
ZITADEL_MASTERKEY=${MASTER_KEY}
RESTIC_PASSWORD=${RESTIC_PASSWORD}
EOF

chmod 600 .env
grep -v 'PASSWORD\|MASTERKEY' .env

Docker Compose

Create the compose.yaml file. PostgreSQL has no ports section, so the database is accessible only to the ZITADEL container on the iam network. The restart: unless-stopped policy restarts the service after a failure but does not replace monitoring.

name: zitadel

services:
  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: zitadel
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: zitadel
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U zitadel -d zitadel"]
      interval: 10s
      timeout: 5s
      retries: 10
    networks:
      - iam

  zitadel:
    image: ${ZITADEL_IMAGE}
    restart: unless-stopped
    command: start-from-init --masterkeyfile /run/secrets/zitadel_masterkey
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      ZITADEL_DATABASE_POSTGRES_HOST: postgres
      ZITADEL_DATABASE_POSTGRES_PORT: "5432"
      ZITADEL_DATABASE_POSTGRES_DATABASE: zitadel
      ZITADEL_DATABASE_POSTGRES_USER_USERNAME: zitadel
      ZITADEL_DATABASE_POSTGRES_USER_PASSWORD: ${POSTGRES_PASSWORD}
      ZITADEL_EXTERNALDOMAIN: ${ZITADEL_DOMAIN}
      ZITADEL_EXTERNALSECURE: "true"
      ZITADEL_TLS_ENABLED: "false"
      ZITADEL_FIRSTINSTANCE_ORG_HUMAN_USERNAME: admin
      ZITADEL_FIRSTINSTANCE_ORG_HUMAN_EMAIL: [email protected]
      ZITADEL_FIRSTINSTANCE_ORG_HUMAN_PASSWORD: CHANGE_THIS_FIRST_PASSWORD
    secrets:
      - zitadel_masterkey
    expose:
      - "8080"
    networks:
      - iam

  caddy:
    image: caddy:2.10-alpine
    restart: unless-stopped
    depends_on:
      - zitadel
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./caddy/Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    networks:
      - iam

secrets:
  zitadel_masterkey:
    file: ./secrets/masterkey

volumes:
  postgres_data:
  caddy_data:
  caddy_config:

networks:
  iam:
    driver: bridge

The initial administrator password in the example must be replaced before starting. For production, use a long random password, then enable MFA after the first login and create a separate administrator account. Do not leave the value CHANGE_THIS_FIRST_PASSWORD.

# Create a master key file matching the value in .env
set -a
. /opt/zitadel/.env
set +a
sudo install -d -m 700 /opt/zitadel/secrets
printf '%s' "$ZITADEL_MASTERKEY" | sudo tee /opt/zitadel/secrets/masterkey > /dev/null
sudo chmod 600 /opt/zitadel/secrets/masterkey
sudo chown -R deploy:deploy /opt/zitadel/secrets

# Validate the Compose configuration without starting containers
docker compose config

# Pull images
docker compose pull

# Start PostgreSQL and ZITADEL in the background
docker compose up -d postgres zitadel

# View the status and latest logs
docker compose ps
docker compose logs --tail=100 zitadel

On the first launch, ZITADEL initializes the database schema. This may take several minutes. If the container exits, examine the logs first instead of rerunning random migration commands. An error in the master key or PostgreSQL connection must be fixed in the configuration.

7. Configuration

Domain and DNS

Create an A record for auth.example.com pointing to the VPS public IPv4 address. If IPv6 is used, add an AAAA record only after verifying that the web server is actually accessible over IPv6. An incorrect AAAA record often causes some users to be unable to open the site.

# Check DNS from the server or local computer
dig +short A auth.example.com
dig +short AAAA auth.example.com

# Check that the name resolves to the expected address
getent ahosts auth.example.com

Caddy and HTTPS

Caddy obtains a certificate automatically if DNS already points to the server, ports 80 and 443 are open, and the domain is accessible from the Internet. Internally, ZITADEL listens for HTTP on port 8080, but the external scheme is set to HTTPS through ZITADEL_EXTERNALSECURE=true.

auth.example.com {
    encode gzip zstd

    reverse_proxy zitadel:8080 {
        header_up Host {host}
        header_up X-Real-IP {remote_host}
        header_up X-Forwarded-Proto {scheme}
        header_up X-Forwarded-For {remote_host}
    }

    log {
        output file /var/log/caddy/zitadel-access.log
        format json
    }
}

Create the directory and start Caddy after validating the file.

# Validate the Caddy configuration inside a temporary container
docker run --rm -v /opt/zitadel/caddy/Caddyfile:/etc/caddy/Caddyfile:ro \
  caddy:2.10-alpine caddy validate --config /etc/caddy/Caddyfile

# Start the reverse proxy and monitor certificate issuance
cd /opt/zitadel
docker compose up -d caddy
docker compose logs -f caddy

HTTPS and Healthcheck Verification

The expected result of the first request is HTTP 200, 301, or an application response without a TLS error. The health endpoint may differ between versions, so check it against the documentation for the installed release. The main signs of proper operation are a successful container start, UI availability, and no database connection errors.

# Check TLS, headers, and the final HTTP response
curl -I https://auth.example.com
curl -fsS https://auth.example.com/debug/healthz || true

# Check containers, ports, and application errors
docker compose ps
docker compose logs --since=10m zitadel | grep -Ei 'error|fatal|panic' || true
sudo ss -tulpn | grep -E ':80|:443|:5432'

Port 5432 must not be listening on a public interface in the output. If it appears, check Compose and remove the ports section from PostgreSQL. Do not expose the administrative console directly through an IP address: use a domain and HTTPS.

First Login and MFA

Open https://auth.example.com/ui/console and log in with the user specified by the first-instance variables. Immediately change the temporary password, confirm the email address after configuring SMTP, and enable MFA through TOTP or WebAuthn.

For daily operations, create a separate administrator account and keep the initial account for emergencies. Minimize roles: an application developer does not need the global IAM administrator role. Enable administrative event logging and regularly review unknown logins.

SMTP

SMTP is used for invitations, access recovery, notifications, and some MFA scenarios. It is better to use a separate mailbox or a transactional SMTP service with a limited purpose. Do not run a mail server on the same VPS without necessity: this will complicate SPF, DKIM, DMARC, and IP reputation.

SMTP can be configured through the ZITADEL console in the instance settings. Specify the SMTP provider hostname, port 587 with STARTTLS, username, password, sender address, and display name. A typical set of variables for automation looks as follows; verify the exact names against the documentation for the ZITADEL version, because instance parameters change between releases.

# Environment fragment for SMTP; store the password only in .env or a secret store
environment:
  ZITADEL_DEFAULTINSTANCE_SMTPCONFIGURATION_SMTP_HOST: smtp.example.net
  ZITADEL_DEFAULTINSTANCE_SMTPCONFIGURATION_SMTP_PORT: "587"
  ZITADEL_DEFAULTINSTANCE_SMTPCONFIGURATION_SMTP_USER: ${SMTP_USER}
  ZITADEL_DEFAULTINSTANCE_SMTPCONFIGURATION_SMTP_PASSWORD: ${SMTP_PASSWORD}
  ZITADEL_DEFAULTINSTANCE_SMTPCONFIGURATION_FROM: "IAM <[email protected]>"
  ZITADEL_DEFAULTINSTANCE_SMTPCONFIGURATION_TLS: "true"

After saving, send a test email from the interface. Check the spam folders, the sender domain's DNS records, and the application logs. Configure SPF and DKIM for the sender domain according to the mail provider's instructions, and start DMARC with a monitoring policy, such as p=none, then tighten it after analyzing the reports.

OIDC Application

To connect an application, create a project and an application of type Web or API in the console. For a web application, specify exact redirect URIs, such as https://app.example.com/oauth/callback. Do not use a wildcard in production unless required by the architecture.

To check the discovery document, request the standard URL:

# Outputs the OpenID Connect discovery document
curl -fsS https://auth.example.com/.well-known/openid-configuration | jq .

# Checks for the main endpoints
curl -fsS https://auth.example.com/.well-known/openid-configuration | \
  jq '{issuer,authorization_endpoint,token_endpoint,jwks_uri}'

The application must verify the issuer, JWT signature using JWKS, token expiration, audience, and scopes. A JWT must not be considered trusted merely because it has the appearance of a token without checking these fields.

8. Backups and Maintenance

What Needs to Be Preserved

  • A PostgreSQL dump or physical copy of the database.
  • The compose.yaml file, .env, Caddyfile, and master key.
  • The Docker volume for PostgreSQL if the physical restoration method is selected.
  • The monitoring configuration and list of DNS records.
  • The restic key and repository password in a separate secure storage location.

Copying only the PostgreSQL directory without a consistent database state is risky. Use pg_dump for a daily logical backup. The database continues running while the dump is created, but restoration should be regularly tested on a separate temporary instance.

Installing restic and Configuring S3

Backups on the same VPS do not protect against disk loss, project deletion, or server compromise. Store them in a separate S3-compatible object storage, preferably in another region. Restic encrypts the contents before uploading them, so the S3 provider cannot see the database data.

# Устанавливаем restic из репозитория Ubuntu
sudo apt update
sudo apt install -y restic postgresql-client

# Создаём каталог для скрипта и ограничиваем права
sudo install -d -m 750 /usr/local/sbin
sudo touch /etc/restic-zitadel.env
sudo chmod 600 /etc/restic-zitadel.env

Fill in /etc/restic-zitadel.env. The AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY values must have access only to the required bucket, without administrative access to the account.

sudo tee /etc/restic-zitadel.env > /dev/null <<'EOF'
export RESTIC_REPOSITORY="s3:https://s3.example.net/iam-backups"
export RESTIC_PASSWORD="replace-with-long-restic-password"
export AWS_ACCESS_KEY_ID="replace-with-limited-access-key"
export AWS_SECRET_ACCESS_KEY="replace-with-secret-key"
export PGUSER="zitadel"
export PGPASSWORD="replace-with-postgres-password"
EOF
sudo chmod 600 /etc/restic-zitadel.env

Initialize the repository once. The restic password cannot be recovered through S3: if it is lost, the encrypted data becomes inaccessible.

# Инициализируем зашифрованный репозиторий
sudo bash -c '. /etc/restic-zitadel.env; restic init'

# Проверяем доступ к репозиторию
sudo bash -c '. /etc/restic-zitadel.env; restic snapshots'

Daily Backup Script

The script first creates a PostgreSQL dump, then archives the configuration and master key, after which it sends the directory to restic. The temporary directory is removed through trap, even if one of the commands fails.

sudo tee /usr/local/sbin/backup-zitadel.sh > /dev/null <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail

source /etc/restic-zitadel.env
BASE=/opt/zitadel
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

mkdir -p "$TMP/db" "$TMP/config"

# Делаем согласованный логический дамп PostgreSQL
docker exec -e PGPASSWORD="$PGPASSWORD" zitadel-postgres-1 \
  pg_dump -U "$PGUSER" -d zitadel --format=custom \
  > "$TMP/db/zitadel-$(date +%F).dump"

# Копируем Compose, env, Caddyfile и master key
cp "$BASE/compose.yaml" "$TMP/config/"
cp "$BASE/.env" "$TMP/config/"
cp "$BASE/caddy/Caddyfile" "$TMP/config/"
cp "$BASE/secrets/masterkey" "$TMP/config/"

# Отправляем файлы в зашифрованный restic-репозиторий
restic backup "$TMP" --tag zitadel --host "$(hostname -s)"

# Удаляем старые точки восстановления
restic forget --tag zitadel --keep-daily 14 --keep-weekly 8 \
  --keep-monthly 12 --prune

# Проверяем случайный набор данных в репозитории
restic check
EOF

sudo chmod 750 /usr/local/sbin/backup-zitadel.sh
sudo /usr/local/sbin/backup-zitadel.sh

The PostgreSQL container name may differ if Compose uses another project name. Check it with docker compose ps and replace zitadel-postgres-1 in the script. A more robust option is to run the dump using docker compose exec -T postgres from the project directory.

Cron and Restoration Testing

Run backups at night, when there are fewer interactive logins. Cron should send errors to the system log; for production, additionally configure external monitoring that checks the freshness of the latest snapshot.

# Запускаем бэкап ежедневно в 03:20
sudo tee /etc/cron.d/zitadel-backup > /dev/null <<'EOF'
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
20 3    root /usr/local/sbin/backup-zitadel.sh > /var/log/zitadel-backup.log 2>&1
EOF
sudo chmod 644 /etc/cron.d/zitadel-backup

# Смотрим последние snapshot
sudo bash -c '. /etc/restic-zitadel.env; restic snapshots --tag zitadel'

The minimum restoration check is to create a temporary PostgreSQL 16 instance, download the latest dump, run pg_restore --list, then restore the database and verify that the tables are present. Perform a full disaster recovery test at least once per quarter.

# Скачиваем последний бэкап во временный каталог
sudo mkdir -p /tmp/zitadel-restore
sudo bash -c '. /etc/restic-zitadel.env; restic restore latest --target /tmp/zitadel-restore'

# Проверяем структуру custom-format дампа
pg_restore --list /tmp/zitadel-restore/tmp/db/zitadel-.dump | head -30

ZITADEL and PostgreSQL Updates

Do not change the image tag without reading the release notes. Before updating, create a fresh dump, snapshot, and copy of the master key. For a small installation, a maintenance window of several minutes is acceptable: stop the application, replace the tag, run docker compose pull, and start the containers.

# Пример контролируемого обновления после проверки release notes
cd /opt/zitadel
sudo /usr/local/sbin/backup-zitadel.sh
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --since=10m zitadel

A rolling update is possible only with an architecture using multiple instances, a migration-compatible schema, and a separate load balancer. One VPS with one container is a maintenance window, not a rolling deployment. Perform the PostgreSQL major upgrade from 16 to 17 separately, after a test restoration and compatibility check with ZITADEL.

9. Troubleshooting and FAQ

Why Is Caddy Not Obtaining a Let’s Encrypt Certificate?

Check that the domain’s A record points to the correct IPv4 address and that the AAAA record does not point to an inaccessible IPv6 address. Then make sure that TCP ports 80 and 443 are allowed in UFW and in the provider’s external firewall. Check docker compose logs caddy. If Nginx or Apache is already running on port 80, stop it or move Caddy to the freed port.

ZITADEL Returns an Error About the External Domain or Redirect URI

Compare ZITADEL_EXTERNALDOMAIN with the actual hostname without the protocol, and set ZITADEL_EXTERNALSECURE to true if the user connects over HTTPS. In the OIDC client, the redirect URI must match completely: the scheme, domain, port, and path are all checked. After changing the environment, recreate the container with docker compose up -d --force-recreate zitadel.

The ZITADEL Container Restarts and Cannot Connect to PostgreSQL

First run docker compose ps and check the database healthcheck. Then inspect docker compose logs postgres and docker compose logs zitadel. The most common causes are an incorrect password, an incorrect service name, a database that has not finished initialization, or a corrupted volume. Do not delete the PostgreSQL volume before checking the backup: this will destroy the data.

SMTP Works, but Messages Are Not Delivered

Check the SMTP host, port 587, STARTTLS, username, and password. Make sure the sender address is allowed by the provider and that the domain has SPF/DKIM. In the ZITADEL logs, look for timeout, authentication failed, and certificate verification error. If the message was accepted by SMTP but did not reach the user, check the queue and the mail service’s own logs, as well as the spam folder.

What Is the Minimum Suitable VPS Configuration?

For a lab, 1–2 vCPUs, 2 GB of RAM, and 30–40 GB of SSD are sufficient, but this configuration handles simultaneous migrations, backups, and other services poorly. For a small production installation, a reasonable minimum is 2 vCPUs, 4 GB of RAM, and 60 GB of SSD/NVMe. If applications, a proxy, and monitoring also run on the same server, choose 4 vCPUs and 8 GB of RAM.

Which Should You Choose for This Task—VPS or Dedicated?

For one ZITADEL instance and several applications, a VPS is usually sufficient: it is cheaper, scales quickly, and does not require maintaining physical equipment yourself. A dedicated server makes sense when strict resource isolation, a large number of users, or co-hosting resource-intensive services is required. However, a dedicated server does not provide high availability by itself; both options require external backups and a recovery plan.

How Can You Check That PostgreSQL Is Not Exposed to the Internet?

Run sudo ss -tulpn | grep 5432 on the server. PostgreSQL should not have a ports section in Compose, only an internal network and, if necessary, expose. Additionally, check the port from an external machine using nmap -Pn -p 5432 PUBLIC_IP. If the port is visible, remove the publication, recreate the container, and check the external firewall rules.

What Should You Do After Losing the Master Key?

The master key cannot be safely replaced by simply editing .env: it is used to work with encrypted data and must correspond to the original installation. Find it in a secure backup or secrets manager. If the key was lost together with the original server, first create a copy of the database and consult the documentation for the specific release; do not attempt to delete tables or run unknown SQL commands.

Why Is the Discovery Endpoint Accessible but Login Does Not Work?

Check the time on the server and client, and verify the issuer, redirect URI, client ID, and secret. Incorrect time breaks validation of JWT and cookie lifetimes. Also make sure that the application is not using an old issuer after a domain change. Check cookies and callback errors in the browser, and enable secure logging on the application side without recording the access token or client secret.

10. Conclusions and Next Steps

A self-hosted ZITADEL with PostgreSQL 16, HTTPS through Caddy, SMTP for system messages, and encrypted backups has been deployed on the VPS. Database access is restricted, IAM is available through the domain, and OIDC discovery can be used to connect applications.

Next, connect external monitoring for HTTPS and certificate expiration, regularly test restoration in a separate environment, and update ZITADEL only after reviewing the release notes. As the load grows, add a separate PostgreSQL instance, a second IAM instance, a load balancer, and fault-tolerant storage; as the team grows, separate organizations, projects, and administrative roles according to the principle of least privilege.

Affiliate links: we may earn a commission, your price stays the same.

Was this guide helpful?

Your feedback helps us improve our guides.

Share this post:

Send this guide to someone who may find it useful.

Telegram VKVK WhatsApp Facebook LinkedIn XX

Zitadel installation on a VPS: self-hosted IAM, PostgreSQL, SSL, SMTP, and backups