Skip to main content

How to Self-Host Matrix + Element 2026

·OSSAlt Team
matrixelementsynapseconduitmessagingslackself-hostingdocker2026
Share:

TL;DR

Matrix is an open, decentralized messaging protocol. Synapse (Apache 2.0, ~12K stars, Python) is the reference homeserver. Element (Apache 2.0) is the most popular Matrix client — web, iOS, Android, and desktop. Together they provide Slack-like team messaging with end-to-end encryption, bridges to external platforms (Slack, Discord, WhatsApp, Telegram), and federation across Matrix homeservers worldwide. Slack Pro costs $7.25/user/month. Self-hosted Matrix is free.

Key Takeaways

  • Matrix: Open protocol — your server, your data, federated with matrix.org and others
  • Synapse: Python-based reference server — feature-complete, higher RAM (~500MB–1GB)
  • Conduit: Rust-based homeserver — lightweight (~50MB RAM), fewer features than Synapse
  • Element: Best Matrix client — web app + iOS/Android + desktop
  • Bridges: Connect Matrix rooms to Slack, Discord, WhatsApp, Telegram channels
  • E2EE: End-to-end encryption in all 1:1 chats and rooms with cross-signing

Matrix vs Mattermost vs Slack

FeatureMatrix + SynapseMattermost CESlack Pro
LicenseApache 2.0MITProprietary
CostFree (hosting)Free (hosting)$7.25/user/mo
FederationYes (Matrix protocol)NoNo
Bridges30+ (Slack, Discord, WA)LimitedYes (paid)
E2EEYesYes (beta)No
ThreadsYesYesYes
CallsYes (Element Call)YesYes
RAM~500MB–1GB~500MB

Docker Setup

# docker-compose.yml
services:
  synapse:
    image: matrixdotorg/synapse:latest
    container_name: synapse
    restart: unless-stopped
    ports:
      - "8448:8448"    # Federation
    volumes:
      - synapse_data:/data
    environment:
      SYNAPSE_CONFIG_PATH: /data/homeserver.yaml
    depends_on:
      - db

  db:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: synapse
      POSTGRES_USER: synapse
      POSTGRES_PASSWORD: "${POSTGRES_PASSWORD}"
      POSTGRES_INITDB_ARGS: "--encoding=UTF-8 --lc-collate=C --lc-ctype=C"
    volumes:
      - synapse_db:/var/lib/postgresql/data

volumes:
  synapse_data:
  synapse_db:

Generate Initial Config

# Generate homeserver.yaml:
docker run --rm \
  -v synapse_data:/data \
  -e SYNAPSE_SERVER_NAME=matrix.yourdomain.com \
  -e SYNAPSE_REPORT_STATS=no \
  matrixdotorg/synapse:latest generate

homeserver.yaml (key settings)

server_name: "matrix.yourdomain.com"
public_baseurl: "https://matrix.yourdomain.com"

database:
  name: psycopg2
  args:
    user: synapse
    password: "${POSTGRES_PASSWORD}"
    database: synapse
    host: db
    cp_min: 5
    cp_max: 10

# Disable open registration:
enable_registration: false

# Allow registration with admin token:
registration_shared_secret: "generate-a-random-secret"

# Enable E2EE key backup:
enable_media_repo: true

listeners:
  - port: 8008
    tls: false
    type: http
    x_forwarded: true
    resources:
      - names: [client, federation]
        compress: false

Part 2: Caddy Configuration

Matrix requires special routing for federation:

matrix.yourdomain.com {
    # Client-Server API:
    reverse_proxy /_matrix/* localhost:8008
    reverse_proxy /_synapse/* localhost:8008
    
    # Well-known delegation:
    handle /.well-known/matrix/client {
        header Content-Type application/json
        header Access-Control-Allow-Origin *
        respond `{"m.homeserver":{"base_url":"https://matrix.yourdomain.com"}}`
    }
    
    handle /.well-known/matrix/server {
        header Content-Type application/json
        respond `{"m.server":"matrix.yourdomain.com:443"}`
    }
}

Option B: Conduit — Lightweight Rust Server

Conduit (Apache 2.0, Rust) is a Matrix homeserver for personal/small team use. ~50MB RAM, single binary.

services:
  conduit:
    image: conduitim/conduit:latest
    container_name: conduit
    restart: unless-stopped
    ports:
      - "6167:6167"
    volumes:
      - conduit_data:/var/lib/conduit
    environment:
      CONDUIT_SERVER_NAME: "matrix.yourdomain.com"
      CONDUIT_DATABASE_PATH: "/var/lib/conduit"
      CONDUIT_DATABASE_BACKEND: "rocksdb"
      CONDUIT_PORT: "6167"
      CONDUIT_MAX_REQUEST_SIZE: "20971520"
      CONDUIT_ALLOW_REGISTRATION: "false"
      CONDUIT_ALLOW_FEDERATION: "true"
      CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
matrix.yourdomain.com {
    reverse_proxy /_matrix/* localhost:6167
    reverse_proxy /_conduit/* localhost:6167
    
    handle /.well-known/matrix/client {
        respond `{"m.homeserver":{"base_url":"https://matrix.yourdomain.com"}}`
    }
}

Conduit tradeoffs: No bridges, no admin API, limited to ~100 users. Great for personal/family use. Use Synapse for team deployments with bridges.


Part 3: Create Admin Account

# With Synapse — create admin user:
docker exec synapse register_new_matrix_user \
  -c /data/homeserver.yaml \
  -u admin \
  -p your-password \
  -a \
  http://localhost:8008

Part 4: Element Web Client

services:
  element-web:
    image: vectorim/element-web:latest
    container_name: element-web
    restart: unless-stopped
    ports:
      - "8080:80"
    volumes:
      - ./element-config.json:/app/config.json:ro
{
  "default_server_config": {
    "m.homeserver": {
      "base_url": "https://matrix.yourdomain.com",
      "server_name": "matrix.yourdomain.com"
    }
  },
  "brand": "Matrix",
  "default_theme": "dark",
  "room_directory": {
    "servers": ["matrix.yourdomain.com"]
  }
}
chat.yourdomain.com {
    reverse_proxy localhost:8080
}

Part 5: Bridges

Bridges connect Matrix rooms to external platforms. Users in the Matrix room see messages from Slack/Discord users and vice versa.

Discord Bridge

services:
  mautrix-discord:
    image: dock.mau.dev/mautrix/discord:latest
    container_name: mautrix-discord
    restart: unless-stopped
    volumes:
      - ./discord-bridge:/data
# Generate config:
docker run --rm -v ./discord-bridge:/data dock.mau.dev/mautrix/discord:latest

# Edit config.yaml:
#   homeserver.address: https://matrix.yourdomain.com
#   homeserver.domain: matrix.yourdomain.com
#   appservice.id: discord

# Register bridge with Synapse (add to homeserver.yaml):
# app_service_config_files:
#   - /data/discord-bridge/registration.yaml

Slack Bridge

services:
  mautrix-slack:
    image: dock.mau.dev/mautrix/slack:latest
    volumes:
      - ./slack-bridge:/data

Available bridges:

  • mautrix-discord — Discord bridge
  • mautrix-slack — Slack bridge
  • mautrix-whatsapp — WhatsApp bridge
  • mautrix-telegram — Telegram bridge
  • mautrix-signal — Signal bridge
  • mx-puppet-twitter — Twitter/X DMs

Part 6: Element Call (Video Calls)

Element Call provides WebRTC video calling without third-party infrastructure:

  1. In Element → Start a call in any room
  2. Or install Element Call standalone: git clone https://github.com/element-hq/element-call
  3. Requires a TURN server for calls outside your LAN:
services:
  coturn:
    image: coturn/coturn:latest
    network_mode: host
    command: >
      -n --log-file=stdout
      --realm=matrix.yourdomain.com
      --static-auth-secret="${TURN_SECRET}"

In homeserver.yaml:

turn_uris:
  - "turn:turn.matrix.yourdomain.com:3478?transport=udp"
  - "turn:turn.matrix.yourdomain.com:3478?transport=tcp"
turn_shared_secret: "your-turn-secret"
turn_user_lifetime: 86400000

Maintenance

# Update Synapse:
docker compose pull
docker compose up -d

# Backup:
# PostgreSQL:
docker exec synapse-db-1 pg_dump -U synapse synapse | gzip > synapse-db-$(date +%Y%m%d).sql.gz

# Media files:
tar -czf synapse-media-$(date +%Y%m%d).tar.gz \
  $(docker volume inspect synapse_synapse_data --format '{{.Mountpoint}}')/media_store

# Purge old room history (reduce database size):
# Admin API: POST /_synapse/admin/v1/purge_history/{roomId}

Why Self-Host Matrix + Element?

The case for self-hosting Matrix + Element comes down to three practical factors: data ownership, cost at scale, and operational control.

Data ownership is the fundamental argument. When you use a SaaS version of any tool, your data lives on someone else's infrastructure subject to their terms of service, their security practices, and their business continuity. If the vendor raises prices, gets acquired, changes API limits, or shuts down, you're left scrambling. Self-hosting Matrix + Element means your data and configuration stay on infrastructure you control — whether that's a VPS, a bare metal server, or a home lab.

Cost at scale matters once you move beyond individual use. Most SaaS equivalents charge per user or per data volume. A self-hosted instance on a $10-20/month VPS typically costs less than per-user SaaS pricing for teams of five or more — and the cost doesn't scale linearly with usage. One well-configured server handles dozens of users for a flat monthly fee.

Operational control is the third factor. The Docker Compose configuration above exposes every setting that commercial equivalents often hide behind enterprise plans: custom networking, environment variables, storage backends, and authentication integrations. You decide when to update, how to configure backups, and what access controls to apply.

The honest tradeoff: you're responsible for updates, backups, and availability. For teams running any production workloads, this is familiar territory. For individuals, the learning curve is real but the tooling (Docker, Caddy, automated backups) is well-documented and widely supported.

Server Requirements and Sizing

Before deploying Matrix + Element, assess your server capacity against expected workload.

Minimum viable setup: A 1 vCPU, 1GB RAM VPS with 20GB SSD is sufficient for personal use or small teams. Most consumer VPS providers — Hetzner, DigitalOcean, Linode, Vultr — offer machines in this range for $5-10/month. Hetzner offers excellent price-to-performance for European and US regions.

Recommended production setup: 2 vCPUs with 4GB RAM and 40GB SSD handles most medium deployments without resource contention. This gives Matrix + Element headroom for background tasks, caching, and concurrent users while leaving capacity for other services on the same host.

Storage planning: The Docker volumes in this docker-compose.yml store all persistent Matrix + Element data. Estimate your storage growth rate early — for data-intensive tools, budget for 3-5x your initial estimate. Hetzner Cloud and Vultr both support online volume resizing without stopping your instance.

Operating system: Any modern 64-bit Linux distribution works. Ubuntu 22.04 LTS and Debian 12 are the most commonly tested configurations. Ensure Docker Engine 24.0+ and Docker Compose v2 are installed — verify with docker --version and docker compose version. Avoid Docker Desktop on production Linux servers; it adds virtualization overhead and behaves differently from Docker Engine in ways that cause subtle networking issues.

Network: Only ports 80 and 443 need to be publicly accessible when running behind a reverse proxy. Internal service ports should be bound to localhost only. A minimal UFW firewall that blocks all inbound traffic except SSH, HTTP, and HTTPS is the single most effective security measure for a self-hosted server.

Backup and Disaster Recovery

Running Matrix + Element without a tested backup strategy is an unacceptable availability risk. Docker volumes are not automatically backed up — if you delete a volume or the host fails, data is gone with no recovery path.

What to back up: The named Docker volumes containing Matrix + Element's data (database files, user uploads, application state), your docker-compose.yml and any customized configuration files, and .env files containing secrets.

Backup approach: For simple setups, stop the container, archive the volume contents, then restart. For production environments where stopping causes disruption, use filesystem snapshots or database dump commands (PostgreSQL pg_dump, SQLite .backup, MySQL mysqldump) that produce consistent backups without downtime.

For a complete automated backup workflow that ships snapshots to S3-compatible object storage, see the Restic + Rclone backup guide. Restic handles deduplication and encryption; Rclone handles multi-destination uploads. The same setup works for any Docker volume.

Backup cadence: Daily backups to remote storage are a reasonable baseline for actively used tools. Use a 30-day retention window minimum — long enough to recover from mistakes discovered weeks later. For critical data, extend to 90 days and use a secondary destination.

Restore testing: A backup that has never been restored is a backup you cannot trust. Once a month, restore your Matrix + Element backup to a separate Docker Compose stack on different ports and verify the data is intact. This catches silent backup failures, script errors, and volume permission issues before they matter in a real recovery.

Security Hardening

Self-hosting means you are responsible for Matrix + Element's security posture. The Docker Compose setup provides a functional base; production deployments need additional hardening.

Always use a reverse proxy: Never expose Matrix + Element's internal port directly to the internet. The docker-compose.yml binds to localhost; Caddy or Nginx provides HTTPS termination. Direct HTTP access transmits credentials in plaintext. A reverse proxy also centralizes TLS management, rate limiting, and access logging.

Strong credentials: Change default passwords immediately after first login. For secrets in docker-compose environment variables, generate random values with openssl rand -base64 32 rather than reusing existing passwords.

Firewall configuration:

ufw default deny incoming
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable

Internal service ports (databases, admin panels, internal APIs) should only be reachable from localhost or the Docker network, never directly from the internet.

Network isolation: Docker Compose named networks keep Matrix + Element's services isolated from other containers on the same host. Database containers should not share networks with containers that don't need direct database access.

VPN access for sensitive services: For internal-only tools, restricting access to a VPN adds a strong second layer. Headscale is an open source Tailscale control server that puts your self-hosted stack behind a WireGuard mesh, eliminating public internet exposure for internal tools.

Update discipline: Subscribe to Matrix + Element's GitHub releases page to receive security advisory notifications. Schedule a monthly maintenance window to pull updated images. Running outdated container images is the most common cause of self-hosted service compromises.

Troubleshooting Common Issues

Container exits immediately or won't start

Check logs first — they almost always explain the failure:

docker compose logs -f matrix

Common causes: a missing required environment variable, a port already in use, or a volume permission error. Port conflicts appear as bind: address already in use. Find the conflicting process with ss -tlpn | grep PORT and either stop it or change Matrix + Element's port mapping in docker-compose.yml.

Cannot reach the web interface

Work through this checklist:

  1. Confirm the container is running: docker compose ps
  2. Test locally on the server: curl -I http://localhost:PORT
  3. If local access works but external doesn't, check your firewall: ufw status
  4. If using a reverse proxy, verify it's running and the config is valid: caddy validate --config /etc/caddy/Caddyfile

Permission errors on volume mounts

Some containers run as a non-root user. If the Docker volume is owned by root, the container process cannot write to it. Find the volume's host path with docker volume inspect VOLUME_NAME, check the tool's documentation for its expected UID, and apply correct ownership:

chown -R 1000:1000 /var/lib/docker/volumes/your_volume/_data

High resource usage over time

Memory or CPU growing continuously usually indicates unconfigured log rotation, an unbound cache, or accumulated data needing pruning. Check current usage with docker stats matrix. Add resource limits in docker-compose.yml to prevent one container from starving others. For ongoing visibility into resource trends, deploy Prometheus + Grafana or Netdata.

Data disappears after container restart

Data stored in the container's writable layer — rather than a named volume — is lost when the container is removed or recreated. This happens when the volume mount path in docker-compose.yml doesn't match where the application writes data. Verify mount paths against the tool's documentation and correct the mapping. Named volumes persist across container removal; only docker compose down -v deletes them.

Keeping Matrix + Element Updated

Matrix + Element follows a regular release cadence. Staying current matters for security patches and compatibility. The update process with Docker Compose is straightforward:

docker compose pull          # Download updated images
docker compose up -d         # Restart with new images
docker image prune -f        # Remove old image layers (optional)

Read the changelog before major version updates. Some releases include database migrations or breaking configuration changes. For major version bumps, test in a staging environment first — run a copy of the service on different ports with the same volume data to validate the migration before touching production.

Version pinning: For stability, pin to a specific image tag in docker-compose.yml instead of latest. Update deliberately after reviewing the changelog. This trades automatic patch delivery for predictable behavior — the right call for business-critical services.

Post-update verification: After updating, confirm Matrix + Element is functioning correctly. Most services expose a /health endpoint that returns HTTP 200 — curl it from the server or monitor it with your uptime tool.


See all open source team communication tools at OSSAlt.com/alternatives/slack.

See open source alternatives to Element on OSSAlt.

The SaaS-to-Self-Hosted Migration Guide (Free PDF)

Step-by-step: infrastructure setup, data migration, backups, and security for 15+ common SaaS replacements. Used by 300+ developers.

Join 300+ self-hosters. Unsubscribe in one click.