23 KiB
Stalwart Mail Server on Ubuntu with Cloudflare, Nginx, and Certbot
This guide deploys a single-node Stalwart mail server on an Ubuntu 24.04 LTS VPS.
It assumes:
- Mail server hostname:
mail.example.com - Email domain:
example.com - Example administrator/contact address:
admin@example.com - Nginx already owns public ports
80and443 - Cloudflare is authoritative for the
example.comDNS zone - Stalwart runs in Docker
- Nginx terminates HTTPS for the WebUI and JMAP
- Stalwart directly handles SMTP, Submission, and IMAP
- Certbot obtains one certificate for
mail.example.com; a renewal hook copies it to a private directory readable by Stalwart
Replace every value written as
REPLACE_WITH_...before running a command or importing a file.
This guide treats
mail.example.comas the server hostname. Mailboxes are addresses such asalice@example.com. If you actually want addresses such asalice@mail.example.com, the DNS and Stalwart domain values must be adjusted.
1. Architecture
Internet
|
+-- TCP 80/443 --> Nginx --> 127.0.0.1:8081 --> Stalwart HTTP/JMAP
|
+-- TCP 25 -------------------------------> Stalwart SMTP
+-- TCP 465 -------------------------------> Stalwart SMTPS
+-- TCP 587 -------------------------------> Stalwart Submission + STARTTLS
+-- TCP 993 -------------------------------> Stalwart IMAPS
Stalwart does not bind to the host's ports 80 or 443, so it does not conflict with the existing Nginx installation.
2. Preflight checklist
Before installing anything, verify that the VPS provider:
- Gives the server a static public IPv4 address.
- Does not block inbound or outbound TCP port
25. - Lets you set reverse DNS (PTR).
- Provides an IP address that is not on major blocklists.
- Allows at least 2 GB RAM for a comfortable small deployment.
Record these values:
VPS IPv4: REPLACE_WITH_VPS_IPV4
Server hostname: mail.example.com
Email domain: example.com
ACME contact email: admin@example.com
Check whether port 25 is already occupied:
sudo ss -ltnp | grep -E ':(25|465|587|993|8081)\b' || true
If Postfix, Exim, Dovecot, or another mail stack is already listening on these ports, stop and resolve that conflict before continuing. Do not remove an existing mail service until you know it is not in use.
3. Configure the hostname and reverse DNS
Set the VPS hostname:
sudo hostnamectl set-hostname mail.example.com
hostnamectl
In the VPS provider's control panel, set the PTR/reverse-DNS record:
REPLACE_WITH_VPS_IPV4 -> mail.example.com
Cloudflare cannot create the PTR record for a normal VPS IP. The IP owner/VPS provider must create it.
Forward and reverse DNS should eventually agree:
mail.example.com -> REPLACE_WITH_VPS_IPV4
REPLACE_WITH_VPS_IPV4 -> mail.example.com
4. Import the bootstrap DNS records into Cloudflare
Create a local file named example.com-bootstrap.zone containing the following text. Replace REPLACE_WITH_VPS_IPV4 first.
$ORIGIN example.com.
$TTL 300
mail.example.com. 300 IN A REPLACE_WITH_VPS_IPV4 ; cf_tags=cf-proxied:false
example.com. 300 IN MX 10 mail.example.com.
example.com. 300 IN TXT "v=spf1 mx -all"
_dmarc.example.com. 300 IN TXT "v=DMARC1; p=none; rua=mailto:dmarc@example.com; adkim=s; aspf=s"
_imaps._tcp.example.com. 300 IN SRV 0 1 993 mail.example.com.
_submissions._tcp.example.com. 300 IN SRV 0 1 465 mail.example.com.
autoconfig.example.com. 300 IN CNAME mail.example.com. ; cf_tags=cf-proxied:false
autodiscover.example.com. 300 IN CNAME mail.example.com. ; cf_tags=cf-proxied:false
Import it in Cloudflare:
- Open Cloudflare Dashboard > example.com > DNS > Records.
- Select Import and Export.
- Import
example.com-bootstrap.zone. - Review every proposed change before confirming it.
- Ensure
mail,autoconfig, andautodiscoverare DNS only (grey cloud), not proxied.
Important:
- Do not delete existing website or verification records.
- If an SPF record already exists, merge its permitted senders into one SPF record. A domain must not publish multiple SPF TXT records.
- If an MX record already exists, changing it switches inbound mail delivery. Do not confirm the MX change until you intend this VPS to receive mail.
- The initial DMARC policy is deliberately
p=nonefor monitoring. Tighten it only after SPF and DKIM have been verified. - DKIM is intentionally absent at this stage because its exact public key must be generated by Stalwart.
- The
cf-proxied:falsetags force Cloudflare DNS-only mode during import.
Cloudflare's mail proxy limitation means the hostname used by MX, SMTP, and IMAP must remain DNS-only. Normal Cloudflare orange-cloud proxying does not proxy arbitrary SMTP or IMAP traffic.
5. Verify initial DNS propagation
Install DNS utilities:
sudo apt update
sudo apt install -y dnsutils
Verify the records:
dig +short A mail.example.com
dig +short MX example.com
dig +short TXT example.com
dig +short TXT _dmarc.example.com
dig +short -x REPLACE_WITH_VPS_IPV4
Do not continue with Certbot until mail.example.com resolves to the VPS and public TCP port 80 reaches this Nginx server.
6. Install Docker, Nginx, Certbot, and firewall tools
The following commands target Ubuntu 24.04 LTS packages:
sudo apt update
sudo apt upgrade -y
sudo apt install -y docker.io docker-compose-v2 nginx snapd ufw curl ca-certificates
sudo systemctl enable --now docker
sudo systemctl enable --now nginx
sudo systemctl enable --now snapd.socket
Install Certbot using the officially recommended Snap package:
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/local/bin/certbot
certbot --version
If /usr/local/bin/certbot already exists, do not recreate the link; verify that the existing certbot command is the intended installation.
7. Configure the firewall
Allow SSH before enabling UFW. Replace OpenSSH if SSH uses a custom port.
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 25/tcp
sudo ufw allow 465/tcp
sudo ufw allow 587/tcp
sudo ufw allow 993/tcp
sudo ufw enable
sudo ufw status verbose
This deployment deliberately does not expose plaintext IMAP 143, POP3 110/995, ManageSieve 4190, or Stalwart's bootstrap HTTP port.
Also open the same ports in any VPS-provider/network firewall.
8. Start Stalwart with Docker Compose
Create the deployment directory and the certificate-copy directory:
sudo install -d -m 0755 /opt/stalwart
sudo install -d -o 2000 -g 2000 -m 0700 /srv/stalwart/tls
cd /opt/stalwart
Create /opt/stalwart/compose.yaml:
services:
stalwart:
image: stalwartlabs/stalwart:v0.16
container_name: stalwart
restart: unless-stopped
environment:
STALWART_PUBLIC_URL: https://mail.example.com
ports:
- "127.0.0.1:8081:8080"
- "25:25"
- "465:465"
- "587:587"
- "993:993"
volumes:
- stalwart-etc:/etc/stalwart
- stalwart-data:/var/lib/stalwart
- /srv/stalwart/tls:/run/stalwart-tls:ro
volumes:
stalwart-etc:
stalwart-data:
v0.16is intentionally pinned because that is the stable minor-series example in the Stalwart documentation when this guide was written (2026-08-12). Before a new installation, check the official release notes and pin the exact tested release you want. Do not replace it blindly withlatestin production.
Start the container:
cd /opt/stalwart
sudo docker compose up -d
sudo docker compose ps
sudo docker logs --tail 100 stalwart
Confirm that Stalwart's web listener is only exposed on loopback:
sudo ss -ltnp | grep -E ':(25|465|587|993|8081)\b'
curl -I http://127.0.0.1:8081/
9. Create a temporary HTTP-only Nginx virtual host
Create /etc/nginx/sites-available/mail.example.com:
server {
listen 80;
listen [::]:80;
server_name mail.example.com;
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Enable and validate it:
sudo ln -s /etc/nginx/sites-available/mail.example.com /etc/nginx/sites-enabled/mail.example.com
sudo nginx -t
sudo systemctl reload nginx
If the symlink already exists, leave it in place and continue after validating its target.
Test the public HTTP route:
curl -I http://mail.example.com/
10. Obtain the public certificate with Certbot
Request a certificate without letting Certbot permanently rewrite the final Nginx configuration:
sudo certbot certonly --nginx \
-d mail.example.com \
-m admin@example.com \
--agree-tos \
--no-eff-email
Confirm that the files exist:
sudo ls -l /etc/letsencrypt/live/mail.example.com/
sudo certbot certificates
11. Copy the certificate securely for Stalwart
The Certbot private key is normally root-only. Do not make /etc/letsencrypt world-readable. Instead, create a controlled deployment script that copies only this certificate into Stalwart's private directory.
Create /usr/local/sbin/deploy-stalwart-certificate:
#!/bin/sh
set -eu
CERT_SOURCE=/etc/letsencrypt/live/mail.example.com
STALWART_TLS_DIR=/srv/stalwart/tls
install -d -o 2000 -g 2000 -m 0700 "$STALWART_TLS_DIR"
install -o 2000 -g 2000 -m 0644 "$CERT_SOURCE/fullchain.pem" "$STALWART_TLS_DIR/fullchain.pem"
install -o 2000 -g 2000 -m 0600 "$CERT_SOURCE/privkey.pem" "$STALWART_TLS_DIR/privkey.pem"
nginx -t
systemctl reload nginx
if docker container inspect stalwart >/dev/null 2>&1; then
docker restart stalwart >/dev/null
fi
Install permissions and run it once:
sudo chmod 0755 /usr/local/sbin/deploy-stalwart-certificate
sudo /usr/local/sbin/deploy-stalwart-certificate
sudo ls -l /srv/stalwart/tls
Register it as a Certbot deploy hook:
sudo install -d -m 0755 /etc/letsencrypt/renewal-hooks/deploy
sudo ln -s /usr/local/sbin/deploy-stalwart-certificate \
/etc/letsencrypt/renewal-hooks/deploy/stalwart-mail
If the hook symlink already exists, inspect it rather than overwriting it.
Test renewal and the hook:
sudo certbot renew --dry-run
12. Replace the Nginx site with the final HTTPS reverse proxy
Replace /etc/nginx/sites-available/mail.example.com with:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
listen [::]:80;
server_name mail.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name mail.example.com;
ssl_certificate /etc/letsencrypt/live/mail.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mail.example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
# Match this to Stalwart's configured maximum message/upload size.
client_max_body_size 100m;
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
}
Validate and reload:
sudo nginx -t
sudo systemctl reload nginx
curl -I https://mail.example.com/
13. Retrieve the temporary Stalwart administrator credentials
sudo docker logs stalwart 2>&1 | grep -A8 'bootstrap mode'
The log should show a temporary username and password. Store the password securely; it is only printed during bootstrap.
14. Complete the initial Stalwart wizard safely
The most reliable method is to use an SSH tunnel and access the bootstrap listener directly.
Run this on your local computer, not on the VPS:
ssh -L 8081:127.0.0.1:8081 REPLACE_WITH_SSH_USER@REPLACE_WITH_VPS_IPV4
Then open this local URL in your browser:
http://127.0.0.1:8081/admin
Use the temporary bootstrap credentials and choose:
Server hostname: mail.example.com
Default email domain: example.com
Storage: local RocksDB defaults (single-node deployment)
Directory: internal directory
Generate DKIM signing keys: enabled
Automatic DNS management: manual
Automatic TLS certificate: disabled/manual
Automatic Stalwart ACME is disabled in this design because Certbot owns the certificate lifecycle. Stalwart will read the Certbot certificate from the mounted private directory.
Finish the wizard, save the permanent administrator credentials, and restart:
cd /opt/stalwart
sudo docker compose restart stalwart
Open the normal administration URL:
https://mail.example.com/admin
15. Register the Certbot certificate in Stalwart
In the Stalwart WebUI, open:
Settings > TLS > Certificates
Create a manual certificate using file sources:
Certificate chain type: File
Certificate chain path: /run/stalwart-tls/fullchain.pem
Private key type: File
Private key path: /run/stalwart-tls/privkey.pem
Then:
- Save the certificate.
- Confirm that Stalwart detects
mail.example.comin its Subject Alternative Names. - Set it as the default certificate under the general TLS/system settings if it is not selected automatically.
- Confirm that the listeners for ports
25,465,587, and993have TLS enabled. - Port
465and993should use implicit TLS. - Port
587should use STARTTLS rather than implicit TLS. - Restart Stalwart once after saving:
sudo docker restart stalwart
16. Trust Nginx's forwarded client IP
For the HTTP listener, configure Stalwart to trust forwarded headers only from the local Nginx proxy.
In the WebUI, find the trusted proxy network setting under:
Settings > Network > Services
Add only the loopback proxy addresses used by this deployment:
127.0.0.1/32
::1/128
Do not trust 0.0.0.0/0 or ::/0. Trusting the entire internet would let clients forge their source IP through forwarded headers.
17. Publish the real DKIM record
In Stalwart, open the example.com domain and view/export its generated DNS zone file. Copy the exact DKIM record generated by Stalwart. It will look similar to this, but the selector and public key will be different:
REPLACE_WITH_SELECTOR._domainkey.example.com. 300 IN TXT "v=DKIM1; k=rsa; p=REPLACE_WITH_STALWART_DKIM_PUBLIC_KEY"
Do not publish the example placeholder. Publish the exact selector and key shown by your server.
You can either:
- Add the DKIM TXT record manually in Cloudflare, or
- Export the complete Stalwart-generated zone file and import it through Cloudflare > DNS > Records > Import and Export.
When importing a complete generated zone, review the diff carefully so existing website records are not removed or incorrectly replaced. Ensure all mail hostnames remain DNS-only.
Verify DKIM after propagation:
dig +short TXT REPLACE_WITH_SELECTOR._domainkey.example.com
18. Create required accounts and aliases
Create at least:
admin@example.com
postmaster@example.com
abuse@example.com
dmarc@example.com
They may be separate accounts or aliases routed to a monitored administrator mailbox. The DMARC record in this guide sends reports to dmarc@example.com, so that address must accept mail.
Create a normal test mailbox, for example:
alice@example.com
Use a unique, strong password and enable two-factor authentication for administrator accounts.
19. Mail-client settings
Use these settings in Thunderbird, Apple Mail, Outlook, or another client:
Username: alice@example.com
Incoming server: mail.example.com
Protocol: IMAP
Port: 993
Connection security: SSL/TLS
Authentication: Normal password or app password
Outgoing server: mail.example.com
Protocol: SMTP
Port: 465
Connection security: SSL/TLS
Authentication: Required
Port 587 with STARTTLS is an alternative submission configuration.
20. Validate the deployment
DNS
dig +short A mail.example.com
dig +short -x REPLACE_WITH_VPS_IPV4
dig +short MX example.com
dig +short TXT example.com
dig +short TXT _dmarc.example.com
dig +short TXT REPLACE_WITH_SELECTOR._domainkey.example.com
Expected essentials:
A: mail.example.com -> VPS IPv4
PTR: VPS IPv4 -> mail.example.com
MX: example.com -> mail.example.com
SPF: v=spf1 mx -all
DKIM: exact public key generated by Stalwart
DMARC: monitoring policy initially
HTTPS and JMAP discovery
curl -fsS https://mail.example.com/.well-known/jmap
curl -fsS https://mail.example.com/.well-known/openid-configuration
All absolute URLs returned by Stalwart should use:
https://mail.example.com
TLS on mail ports
openssl s_client -connect mail.example.com:993 -servername mail.example.com </dev/null
openssl s_client -connect mail.example.com:465 -servername mail.example.com </dev/null
openssl s_client -starttls smtp -connect mail.example.com:587 -servername mail.example.com </dev/null
openssl s_client -starttls smtp -connect mail.example.com:25 -servername mail.example.com </dev/null
Confirm that the presented certificate is valid for mail.example.com and that the chain verifies successfully.
Service and logs
sudo docker compose -f /opt/stalwart/compose.yaml ps
sudo docker logs --tail 200 stalwart
sudo journalctl -u nginx -n 100 --no-pager
sudo ss -ltnp | grep -E ':(25|80|443|465|587|993|8081)\b'
Send/receive tests
- Send from
alice@example.comto an external Gmail or Outlook mailbox. - Inspect the received message headers for SPF, DKIM, and DMARC results.
- Reply from the external mailbox to
alice@example.com. - Confirm the reply reaches Stalwart.
- Check both inbox and spam folders during early testing.
Do not tighten DMARC until legitimate messages consistently pass SPF and/or DKIM alignment.
21. Security hardening after verification
- Keep
127.0.0.1:8081bound to loopback only. - Do not expose Stalwart's bootstrap/recovery listener publicly.
- Keep Cloudflare mail records DNS-only.
- Disable unused Stalwart listeners such as POP3 and plaintext IMAP.
- Enable two-factor authentication for administrators.
- Prefer application passwords for mail clients where supported.
- Rate-limit authentication and monitor automatic bans.
- Restrict
/adminby VPN or source IP in Nginx if operationally possible. - Keep Ubuntu, Nginx, Docker, and Stalwart patched.
- Pin Stalwart releases and test upgrades against a backup before production rollout.
- Monitor disk space, delivery queues, TLS expiry, logs, and abuse complaints.
Example Nginx restriction if administration is only allowed from one trusted IP:
location ^~ /admin {
allow REPLACE_WITH_TRUSTED_ADMIN_IPV4;
deny all;
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
Only add this after confirming that the trusted address is static and that you have a recovery path.
22. Backups
The two Docker volumes contain configuration and local Stalwart data. Stop the service briefly for a simple consistent single-node filesystem backup:
sudo install -d -m 0700 /srv/backups/stalwart
cd /opt/stalwart
sudo docker compose stop stalwart
sudo docker run --rm \
-v stalwart-etc:/source:ro \
-v /srv/backups/stalwart:/backup \
alpine:3.22 \
tar -czf /backup/stalwart-etc.tar.gz -C /source .
sudo docker run --rm \
-v stalwart-data:/source:ro \
-v /srv/backups/stalwart:/backup \
alpine:3.22 \
tar -czf /backup/stalwart-data.tar.gz -C /source .
sudo docker compose start stalwart
sudo ls -lh /srv/backups/stalwart
Also back up:
/opt/stalwart/compose.yaml
/etc/nginx/sites-available/mail.example.com
/usr/local/sbin/deploy-stalwart-certificate
Cloudflare DNS zone export
Copy backups to another machine or object-storage account. A backup stored only on the mail VPS does not protect against VPS loss. Test restoration periodically.
For larger deployments or external databases/object stores, use the backup procedure specific to that storage backend rather than copying local volumes blindly.
23. Upgrade procedure
Never switch a production server directly to latest.
- Read the Stalwart release notes and migration guide.
- Take and verify a backup.
- Test the target version in a staging environment.
- Change only the pinned image tag in
/opt/stalwart/compose.yaml. - Pull and restart:
cd /opt/stalwart
sudo docker compose pull
sudo docker compose up -d
sudo docker compose ps
sudo docker logs --tail 200 stalwart
- Retest SMTP, IMAP, JMAP, authentication, DKIM signing, and inbound/outbound delivery.
24. Common failure modes
Cloudflare shows an orange cloud for mail
Set mail.example.com to DNS-only. SMTP and IMAP should not point at a normally proxied Cloudflare record.
Certbot validation fails
Check:
dig +short A mail.example.com
sudo ufw status
sudo ss -ltnp | grep ':80\b'
curl -I http://mail.example.com/
sudo nginx -t
Web sign-in redirects to the wrong address
Confirm the container environment contains:
STALWART_PUBLIC_URL: https://mail.example.com
Then restart the container and inspect the discovery documents.
Every web request appears to come from localhost
Verify Nginx forwards X-Forwarded-For, and configure Stalwart to trust forwarded headers only from 127.0.0.1/32 and ::1/128.
IMAP/SMTP presents a self-signed certificate
Confirm:
sudo ls -l /srv/stalwart/tls
sudo docker exec stalwart ls -l /run/stalwart-tls
Then verify that the manual Certificate object uses these exact container paths:
/run/stalwart-tls/fullchain.pem
/run/stalwart-tls/privkey.pem
Restart Stalwart after correcting the certificate record.
Outbound mail does not leave the server
Check whether the VPS provider blocks outbound TCP port 25. If it does, request removal of the block or configure a reputable SMTP relay in Stalwart.
Messages go to spam
Verify A/PTR agreement, SPF, DKIM, DMARC, IP reputation, message content, sending volume, and complaint/bounce handling. A technically correct server does not automatically receive good deliverability from a new or previously abused IP.
25. Reference documentation
- Stalwart Docker installation: https://stalw.art/docs/install/platform/docker/
- Stalwart Nginx reverse proxy: https://stalw.art/docs/server/reverse-proxy/nginx/
- Stalwart reverse-proxy concepts: https://stalw.art/docs/server/reverse-proxy/
- Stalwart DNS setup: https://stalw.art/docs/install/dns/
- Stalwart TLS certificates: https://stalw.art/docs/domains/tls-certificates/
- Stalwart security checklist: https://stalw.art/docs/install/security/
- Cloudflare DNS import/export: https://developers.cloudflare.com/dns/manage-dns-records/how-to/import-and-export/
- Certbot Nginx instructions: https://certbot.eff.org/instructions?ws=nginx&os=snap
Last reviewed: 2026-08-12.
This is an operational template, not a substitute for testing, monitoring, backups, abuse prevention, and a documented recovery plan.