Deploying a Matrix Synapse Chat Server with Element on Ubuntu 22.04
Matrix is a set of open APIs for decentralized and end-to-end encrypted communication. It works across a collection of federation servers to deliver instant messages, Voice over IP (VoIP), and Internet of Things (IoT) communication in real time. Matrix uses homeservers to store account information and chat history, and federation works like email, so you can either use a server hosted by somebody else or host your own. Synapse is the homeserver implementation maintained by the Matrix.org team, and Element is the most widely used Matrix client.
This guide walks through running a self-hosted chat server on an Ubuntu 22.04 server. By the end, you'll have a Synapse homeserver backed by PostgreSQL, served over HTTPS through Nginx, with a Coturn TURN server for voice and video calls and a self-hosted Element web client.
Before you begin, you need an Ubuntu 22.04 server with at least 2 GB of RAM and one vCPU core as a non-root user with sudo privileges, updated packages, and DNS A records for matrix.example.com, element.example.com, and coturn.example.com pointing to your server's public IP address.
Configure the Firewall
Synapse serves both client traffic and federation traffic, and each arrives on a different port. Open those ports before installing the packages so that certificate issuance and federation succeed once the services start.
- Allow HTTP traffic:
$ sudo ufw allow http - Allow HTTPS traffic:
$ sudo ufw allow https - Allow the Matrix federation port:
$ sudo ufw allow 8448 - Review the active rules:
$ sudo ufw status
The output displays 80, 443, and 8448 with an ALLOW action.
Install Matrix Synapse
Ubuntu does not package Synapse, so the packages come from the official Matrix.org APT repository. Signing the repository with a dedicated keyring restricts that key to this repository alone.
- Download the repository signing key:
$ sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg - Add the Matrix repository and bind it to the keyring:
$ echo "deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/matrix-org.list - Update the package index:
$ sudo apt update - Install Synapse:
$ sudo apt install matrix-synapse-py3
The installer prompts for a server name. Enter your Matrix domain name, such as example.com. Enter N to decline reporting of anonymized statistics.
Note: The server name becomes part of every user ID on the homeserver and is difficult to change after users exist. To change it later, edit the /etc/matrix-synapse/conf.d/server_name.yaml file.
Install and Configure PostgreSQL
Synapse uses SQLite by default, which does not perform well enough for a production homeserver. PostgreSQL is the supported production database, and Synapse expects it to be created with a specific locale and character encoding.
- Install PostgreSQL:
$ sudo apt install postgresql postgresql-contrib - Open the PostgreSQL shell:
$ sudo -u postgres psql - Create the Synapse database role. Replace
DB-PASSWORDwith a strong password:postgres=# CREATE ROLE synapse LOGIN PASSWORD 'DB-PASSWORD'; - Create the Synapse database owned by that role:
postgres=# CREATE DATABASE synapsedb OWNER synapse LOCALE 'C' ENCODING 'UTF8' TEMPLATE template0;
Synapse refuses to start against a database created with any other collation.
- Exit the shell:
postgres=# \q
Install Nginx
Nginx terminates TLS and proxies client and federation requests to Synapse. Ubuntu 22.04 ships an older Nginx release, so install the current version from the official Nginx repository.
Download the Nginx signing key:
$ curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg > /dev/nullAdd the Nginx repository:
$ echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg arch=amd64] http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.listVerify that the repository file exists:
$ cat /etc/apt/sources.list.d/nginx.listAn empty result means the file was not written, and apt installs the older Ubuntu package instead.
Update the package index:
$ sudo apt updateInstall Nginx:
$ sudo apt install nginxStart Nginx:
$ sudo systemctl start nginx
Issue TLS Certificates
Matrix clients and federating servers both require valid TLS. Certbot issues free certificates from Let's Encrypt, and the Nginx plugin handles the HTTP challenge automatically.
Install Certbot and the Nginx plugin:
$ sudo apt install certbot python3-certbot-nginxVerify the installed version:
$ certbot --versionIssue the certificate for the Matrix subdomain. Replace
n***@example.comwith your email address andmatrix.example.comwith your Matrix subdomain:$ sudo certbot certonly --nginx --agree-tos --no-eff-email --staple-ocsp --preferred-challenges http -m n***@example.com -d matrix.example.comGenerate a Diffie-Hellman parameter file:
$ sudo openssl dhparam -dsaparam -out /etc/ssl/certs/dhparam.pem 4096The command takes several minutes to complete.
Verify that automatic renewal works:
$ sudo certbot renew --dry-run
Configure Synapse
The package manager overwrites the main Synapse configuration file during updates, so production settings belong in separate files in the drop-in configuration directory. Synapse merges every file in that directory at startup, which keeps your changes safe across upgrades.
Create the database configuration file:
$ sudo nano /etc/matrix-synapse/conf.d/database.yamlAdd the following configuration. Replace
DB-PASSWORDwith the password you set in Install and Configure PostgreSQL:database: name: psycopg2 args: user: synapse password: 'DB-PASSWORD' database: synapsedb host: localhost cp_min: 5 cp_max: 10Save and close the file.
name: psycopg2selects the PostgreSQL driver instead of the default SQLite driver, andcp_min/cp_maxset the minimum and maximum size of the database connection pool.Generate a registration shared secret:
$ echo "registration_shared_secret: ' $(cat /dev/urandom | tr -cd '[:alnum:]' | fold -w 256 | head -n 1) '" | sudo tee /etc/matrix-synapse/conf.d/registration_shared_secret.yamlRestart Synapse so that it connects to PostgreSQL and loads the shared secret:
$ sudo systemctl restart matrix-synapseVerify that Synapse is running:
$ sudo systemctl status matrix-synapseVerify that the output reports
Active: active (running). Synapse creates its schema insynapsedbon this first start, which takes up to a minute.Create an administrator account. Enter a username and password when prompted, then type
yesto grant administrator rights:$ register_new_matrix_user -c /etc/matrix-synapse/conf.d/registration_shared_secret.yaml http://localhost:8008Create a registration configuration file to allow public sign-ups:
$ sudo nano /etc/matrix-synapse/conf.d/registration.yamlAdd the following configuration to enable registration with email verification. Replace
SMTP-PASSWORDwith the password for the sending mailbox, and the remaining mail server values with your own:enable_registration: true registrations_require_3pid: - email email: smtp_host: mail.example.com smtp_port: 587 # If the mail server has no authentication, skip these two lines smtp_user: 'n******@example.com' smtp_pass: 'SMTP-PASSWORD' # Optional, require encryption with STARTTLS require_transport_security: true app_name: 'Example Chat' # defines value for %(app)s in notif_from and email subject notif_from: " %(app)s <n******@example.com>"To skip verification instead, replace the
registrations_require_3pidandemailblocks with the following line:enable_registration_without_verification: trueCreate a presence configuration file:
$ sudo nano /etc/matrix-synapse/conf.d/presence.yamlAdd the following configuration:
presence: enabled: falseSynapse tracks each user's online status by default, which raises CPU usage on small servers. Disabling presence removes that overhead.
Restart Synapse to apply the changes:
$ sudo systemctl restart matrix-synapse
Configure Nginx
Synapse listens only on the loopback interface and does not terminate TLS itself. Nginx accepts public traffic, handles TLS, and forwards the Matrix client and federation requests to Synapse.
Open the main Nginx configuration file:
$ sudo nano /etc/nginx/nginx.confAdd the following directive inside the
httpblock, before theinclude /etc/nginx/conf.d/*.conf;line:server_names_hash_bucket_size 64;Create the Synapse site configuration:
$ sudo nano /etc/nginx/conf.d/synapse.confAdd the following configuration. Replace
matrix.example.comwith your Matrix subdomain:# enforce HTTPS server { listen 80; listen [::]:80; server_name matrix.example.com; return 301 https://$host$request_uri; } server { server_name matrix.example.com; # Client port listen 443 ssl; listen [::]:443 ssl; # Federation port listen 8448 ssl default_server; listen [::]:8448 ssl default_server; http2 on; access_log /var/log/nginx/synapse.access.log; error_log /var/log/nginx/synapse.error.log; # TLS configuration ssl_certificate /etc/letsencrypt/live/matrix.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/matrix.example.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/matrix.example.com/chain.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_stapling_verify on; ssl_dhparam /etc/ssl/certs/dhparam.pem; location ~ ^(/_matrix|/_synapse/client) { proxy_pass http://localhost:8008; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; # Increase client_max_body_size to match max_upload_size in homeserver.yaml client_max_body_size 50M; } }http2 on;enables HTTP/2 for the server block (Nginx 1.25.1+ deprecates the olderlisten ... http2form), andclient_max_body_sizeraises the upload limit from the 1 MB Nginx default so that media uploads succeed.Test the configuration syntax:
$ sudo nginx -tRestart Nginx:
$ sudo systemctl restart nginx
Install and Configure Coturn
Voice and video calls between clients behind NAT require a Traversal Using Relays around NAT (TURN) server. Coturn relays that media, and Synapse hands out short-lived credentials generated from a shared secret.
Install Coturn:
$ sudo apt install coturnAllow the TURN control ports:
$ sudo ufw allow 3478Allow the TURN TLS port:
$ sudo ufw allow 5349Allow the media relay port range:
$ sudo ufw allow 49152:65535/udpIssue a certificate for the Coturn subdomain. Replace
coturn.example.comwith your Coturn subdomain:$ sudo certbot certonly --nginx -d coturn.example.comBack up the default configuration file:
$ sudo mv /etc/turnserver.conf /etc/turnserver.conf.bakGenerate an authentication secret and write it to a new configuration file:
$ echo "static-auth-secret= $(cat /dev/urandom | tr -cd '[:alnum:]' | fold -w 256 | head -n 1) " | sudo tee /etc/turnserver.confThe command prints the generated secret. Copy the value, because Synapse needs it later.
Open the Coturn configuration file:
$ sudo nano /etc/turnserver.confAdd the following configuration below the authentication secret. Replace
coturn.example.comwith your Coturn subdomain:use-auth-secret realm = coturn.example.com cert = /etc/letsencrypt/live/coturn.example.com/fullchain.pem pkey = /etc/letsencrypt/live/coturn.example.com/privkey.pem # VoIP is UDP, no need for TCP no-tcp-relay # Do not allow traffic to private IP ranges no-multicast-peers denied-peer-ip = 0.0.0.0-0.255.255.255 denied-peer-ip = 10.0.0.0-10.255.255.255 denied-peer-ip = 100.64.0.0-100.127.255.255 denied-peer-ip = 127.0.0.0-127.255.255.255 denied-peer-ip = 169.254.0.0-169.254.255.255 denied-peer-ip = 172.16.0.0-172.31.255.255 denied-peer-ip = 192.0.0.0-192.0.0.255 denied-peer-ip = 192.0.2.0-192.0.2.255 denied-peer-ip = 192.88.99.0-192.88.99.255 denied-peer-ip = 192.168.0.0-192.168.255.255 denied-peer-ip = 198.18.0.0-198.19.255.255 denied-peer-ip = 198.51.100.0-198.51.100.255 denied-peer-ip = 203.0.113.0-203.0.113.255 denied-peer-ip = 240.0.0.0-255.255.255.255 denied-peer-ip = ::1 denied-peer-ip = 64:ff9b::-64:ff9b::ffff:ffff denied-peer-ip = ::ffff:0.0.0.0-::ffff:255.255.255.255 denied-peer-ip = 100::-100::ffff:ffff:ffff:ffff denied-peer-ip = 2001::-2001:1ff:ffff:ffff:ffff:ffff:ffff:ffff denied-peer-ip = 2002::-2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff denied-peer-ip = fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff denied-peer-ip = fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff # Limit number of sessions per user user-quota = 12 # Limit total number of sessions total-quota = 1200use-auth-secretenables the shared-secret authentication mode that Synapse expects, anddenied-peer-ipblocks relaying to private and reserved address ranges, preventing the TURN server from reaching internal services.Restart Coturn:
$ sudo systemctl restart coturnCreate the Synapse TURN configuration file:
$ sudo nano /etc/matrix-synapse/conf.d/turn.yamlAdd the following configuration. Replace
YOUR-STATIC-AUTH-SECRETwith thestatic-auth-secretvalue from/etc/turnserver.conf, andcoturn.example.comwith your Coturn subdomain:turn_uris: - "turn:coturn.example.com?transport=udp" - "turn:coturn.example.com?transport=tcp" turn_shared_secret: 'YOUR-STATIC-AUTH-SECRET' turn_user_lifetime: 86400000 turn_allow_guests: TrueRestart Synapse to apply the configuration:
$ sudo systemctl restart matrix-synapse
Connect a Matrix Client
The homeserver is now reachable over HTTPS, so any Matrix client can sign in to it. Use a hosted client to confirm the deployment before setting up your own Element instance.
- Open a Matrix client such as the Element web
Comments
No comments yet. Start the discussion.