Deploying docker-mailserver
Introduction
docker-mailserver (DMS) is a full-featured, production-ready mail server running entirely inside a Docker container. It combines Postfix for SMTP, Dovecot for IMAP/POP3, and various security tools into a cohesive, easy-to-configure package that rivals traditional enterprise mail solutions.
Unlike hosted email services, docker-mailserver gives you complete control over your email infrastructure. Your emails are stored on your own servers, encrypted in transit and at rest, and managed according to your own policies. The project prioritizes security, providing built-in spam filtering, virus scanning, DKIM signing, and TLS encryption.
Key highlights of docker-mailserver:
- Complete Mail Stack: Postfix (SMTP), Dovecot (IMAP/POP3), and security tools in one container
- Security First: DKIM, DMARC, SPF, and automatic TLS with Let’s Encrypt support
- Spam Protection: SpamAssassin integration with automatic learning
- Virus Scanning: ClamAV integration for malware detection
- Multiple Domains: Host email for unlimited domains from a single instance
- Fail2Ban: Automatic blocking of brute-force attacks
- Account Management: Simple setup script for managing users and aliases
- Quota Support: Set storage limits per user
- OAuth Support: Modern authentication options including OAuth2
- 100% Open Source: MIT licensed with excellent documentation
This guide walks through deploying docker-mailserver on Klutch.sh, configuring DNS records, and managing a production mail server.
Why Deploy docker-mailserver on Klutch.sh
Deploying docker-mailserver on Klutch.sh provides several advantages for your email infrastructure:
Simplified Deployment: Klutch.sh handles container orchestration while you focus on email configuration and DNS setup.
Persistent Storage: Attach volumes for mail storage, configuration, and logs that persist across updates.
Scalable Resources: Allocate CPU and memory based on your email volume and user count.
Custom Domains: Essential for email - use your own domains with proper DNS configuration.
Always-On Availability: Your mail server remains operational 24/7, critical for email reliability.
Centralized Management: Manage your entire email infrastructure from a single deployment.
Prerequisites
Before deploying docker-mailserver on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your configuration
- One or more domain names with full DNS control
- Understanding of email protocols and DNS records (MX, SPF, DKIM, DMARC)
- Ability to configure reverse DNS (rDNS/PTR records)
- TLS certificates for your mail domain
Understanding docker-mailserver Architecture
docker-mailserver combines multiple components:
Postfix (MTA): The Mail Transfer Agent handles SMTP for sending and receiving email between servers.
Dovecot (MDA): The Mail Delivery Agent provides IMAP and POP3 access for email clients.
SpamAssassin: Analyzes incoming email and scores it for spam likelihood.
ClamAV: Scans attachments and email content for viruses and malware.
OpenDKIM: Signs outgoing mail with DKIM signatures for authentication.
Fail2Ban: Monitors logs and blocks IPs that show malicious patterns.
Amavis: Bridges Postfix to SpamAssassin and ClamAV for content filtering.
Preparing Your Repository
Create a GitHub repository with your docker-mailserver configuration.
Repository Structure
mailserver-deploy/├── Dockerfile├── config/│ ├── postfix-main.cf│ └── user-patches.sh├── setup/│ └── init.sh└── .dockerignoreCreating the Dockerfile
Create a Dockerfile for your mail server:
FROM docker.io/mailserver/docker-mailserver:latest
# Copy configurationCOPY config/ /tmp/docker-mailserver/
# Copy initialization scriptCOPY setup/init.sh /usr/local/bin/RUN chmod +x /usr/local/bin/init.sh
# Create directoriesRUN mkdir -p /var/mail /var/mail-state /var/log/mail
# Expose mail ports# SMTPEXPOSE 25# ESMTP with STARTTLSEXPOSE 587# ESMTP over TLSEXPOSE 465# IMAPEXPOSE 143# IMAP over TLSEXPOSE 993# POP3EXPOSE 110# POP3 over TLSEXPOSE 995
# Health checkHEALTHCHECK --interval=60s --timeout=30s --start-period=120s --retries=3 \ CMD supervisorctl status || exit 1
# Environment variables with defaultsENV ENABLE_SPAMASSASSIN=1ENV ENABLE_CLAMAV=1ENV ENABLE_FAIL2BAN=1ENV ENABLE_POSTGREY=0ENV ONE_DIR=1ENV DMS_DEBUG=0ENV POSTFIX_MESSAGE_SIZE_LIMIT=52428800ENV ENABLE_AMAVIS=1
# Use supervisor entrypoint from base imageCreating Postfix Configuration
Create config/postfix-main.cf for custom Postfix settings:
# Custom Postfix configuration
# Message size limit (50MB)message_size_limit = 52428800
# Mailbox size limit (0 = unlimited, use quotas instead)mailbox_size_limit = 0
# HELO restrictionssmtpd_helo_required = yessmtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname
# Sender restrictionssmtpd_sender_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_sender, reject_unknown_sender_domain
# Relay restrictionssmtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destinationCreating User Patches Script
Create config/user-patches.sh for custom modifications:
#!/bin/bash
# This script is executed during container startup# Add custom configuration here
echo "Applying custom patches..."
# Example: Add custom spam rules# echo "score CUSTOM_RULE 5.0" >> /etc/spamassassin/local.cf
echo "Custom patches applied."Creating Initialization Script
Create setup/init.sh:
#!/bin/bash
# Initialize docker-mailserver configuration
# Create data directories if they don't existmkdir -p /var/mailmkdir -p /var/mail-statemkdir -p /var/log/mailmkdir -p /tmp/docker-mailserver
# Set permissionschown -R 5000:5000 /var/mailchmod 755 /var/mail
echo "Initialization complete."Creating the .dockerignore File
Create a .dockerignore file:
.git.github*.mdLICENSE.gitignore.DS_StoreDeploying docker-mailserver on Klutch.sh
Follow these steps to deploy your mail server:
- Port 25: SMTP (inbound mail)
- Port 587: Submission (authenticated sending)
- Port 465: SMTPS (submission over TLS)
- Port 993: IMAPS (secure IMAP)
- Port 995: POP3S (secure POP3)
- Set MX record pointing to your mail server
- Configure SPF record
- Set up DMARC policy
- Outbound email delivery
- Inbound email receipt
- Spam filtering
- DKIM signing
Plan Your DNS Configuration
Before deployment, plan the DNS records you’ll need:
| Record Type | Name | Value |
|---|---|---|
| A | Your server IP | |
| MX | @ | mail.example.com (priority 10) |
| TXT | @ | v=spf1 mx -all |
| TXT | _dmarc | v=DMARC1; p=quarantine; rua=mailto:postmaster@example.com |
| TXT | mail._domainkey | (DKIM public key - generated after setup) |
Push Your Repository to GitHub
Initialize and push your configuration:
git initgit add .git commit -m "Initial docker-mailserver configuration"git remote add origin https://github.com/yourusername/mailserver-deploy.gitgit push -u origin mainCreate a New Project on Klutch.sh
Navigate to the Klutch.sh dashboard and create a new project for your mail infrastructure.
Create a New App
Create a new app within your project and connect your GitHub repository.
Configure Traffic Settings
docker-mailserver requires multiple ports. Configure:
Set Environment Variables
Configure the following environment variables:
| Variable | Value |
|---|---|
HOSTNAME | mail.example.com |
DOMAINNAME | example.com |
ENABLE_SPAMASSASSIN | 1 |
ENABLE_CLAMAV | 1 |
ENABLE_FAIL2BAN | 1 |
SSL_TYPE | letsencrypt |
POSTMASTER_ADDRESS | postmaster@example.com |
PERMIT_DOCKER | none |
Attach Persistent Volumes
Add persistent volumes for mail storage:
| Mount Path | Recommended Size | Purpose |
|---|---|---|
/var/mail | 100+ GB | User mailboxes |
/var/mail-state | 10 GB | Service state and databases |
/var/log/mail | 5 GB | Mail server logs |
/tmp/docker-mailserver | 1 GB | Configuration and DKIM keys |
Size your mail volume based on expected usage and retention policies.
Deploy Your Application
Click Deploy to build and start docker-mailserver.
Configure DNS Records
After deployment, configure your DNS records as planned. Most importantly:
Generate DKIM Keys
After the container is running, generate DKIM keys:
# Access containersetup config dkimAdd the generated public key to your DNS as a TXT record.
Add Email Accounts
Create your first email account:
setup email add user@example.comTest Your Configuration
Send test emails to verify:
Managing Email Accounts
Adding Users
Add new email accounts using the setup script:
setup email add user@example.comYou’ll be prompted for a password, or generate one:
setup email add user@example.com "$(openssl rand -base64 16)"Updating Passwords
Change user passwords:
setup email update user@example.comRemoving Users
Delete email accounts:
setup email del user@example.comSetting Quotas
Configure mailbox size limits:
setup quota set user@example.com 5GCreating Aliases
Set up email aliases:
setup alias add alias@example.com target@example.comMulti-Domain Configuration
Adding Domains
docker-mailserver supports multiple domains:
- Add MX record for the new domain
- Configure SPF, DKIM, and DMARC
- Add user accounts for the new domain
Per-Domain DKIM
Generate DKIM keys for each domain:
setup config dkim domain example.comsetup config dkim domain example.orgDomain-Specific Settings
Configure per-domain settings through environment variables or Postfix configuration.
Security Configuration
TLS Certificates
Configure TLS certificates:
Let’s Encrypt (Recommended):
SSL_TYPE=letsencryptManual Certificates:
SSL_TYPE=manualSSL_CERT_PATH=/path/to/fullchain.pemSSL_KEY_PATH=/path/to/privkey.pemSPF Records
Configure SPF to authorize your mail server:
v=spf1 mx a:mail.example.com -allOptions:
+all: Allow all (not recommended)~all: Soft fail-all: Hard fail (recommended)
DKIM Configuration
DKIM signs outgoing mail:
- Generate keys with
setup config dkim - Add public key to DNS
- Verify with online DKIM testers
DMARC Policy
Configure DMARC for authentication policy:
v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100Policy options:
p=none: Monitor onlyp=quarantine: Mark as spamp=reject: Reject unauthenticated mail
Spam and Virus Protection
SpamAssassin Configuration
SpamAssassin scores incoming mail:
| Score | Typical Action |
|---|---|
| < 5.0 | Deliver normally |
| 5.0-10.0 | Mark as spam |
| > 10.0 | Reject |
Custom rules in /etc/spamassassin/local.cf:
# Whitelist specific senderswhitelist_from trusted@example.com
# Blacklist domainsblacklist_from *@spamdomain.com
# Adjust scoresscore RULE_NAME 0.0ClamAV Updates
ClamAV virus definitions update automatically. Monitor logs for update status.
Fail2Ban Rules
Fail2Ban protects against brute-force attacks:
# Check banned IPsfail2ban-client status postfix-sasl
# Unban an IPfail2ban-client set postfix-sasl unbanip 1.2.3.4Monitoring and Logs
Viewing Logs
Access mail server logs:
# All mail logstail -f /var/log/mail/mail.log
# Postfix specifictail -f /var/log/mail/postfix.log
# Dovecot specifictail -f /var/log/mail/dovecot.logQueue Management
Monitor and manage the mail queue:
# View queuepostqueue -p
# Flush queuepostqueue -f
# Delete specific messagepostsuper -d MESSAGE_ID
# Delete all queued mailpostsuper -d ALLService Status
Check component status:
supervisorctl statusProduction Best Practices
Resource Allocation
- CPU: 2+ cores for spam/virus scanning
- Memory: 4GB minimum, 8GB+ recommended with ClamAV
- Storage: Scale based on users and retention
Backup Strategy
Regular backups should include:
- Mail storage (
/var/mail) - Configuration and state (
/var/mail-state) - Custom configurations
- DKIM private keys
Monitoring Recommendations
- Monitor disk space (mail storage fills quickly)
- Track mail queue length
- Alert on Fail2Ban events
- Monitor delivery success rates
Troubleshooting Common Issues
Mail Not Delivering
Symptoms: Sent emails never arrive.
Solutions:
- Check mail queue for stuck messages
- Verify DNS records (MX, SPF)
- Check recipient server rejection reasons
- Review Postfix logs for errors
DKIM Validation Failing
Symptoms: DKIM signatures don’t validate.
Solutions:
- Verify DNS TXT record is correct
- Check for line breaks in DNS record
- Ensure selector matches configuration
- Test with DKIM validators online
High Spam Scores
Symptoms: Legitimate mail marked as spam.
Solutions:
- Train SpamAssassin with ham/spam samples
- Whitelist known senders
- Adjust rule scores
- Check sender reputation
Connection Refused
Symptoms: Cannot connect to mail server.
Solutions:
- Verify ports are exposed correctly
- Check firewall rules
- Ensure services are running
- Review connection logs
Additional Resources
- docker-mailserver Documentation
- docker-mailserver GitHub Repository
- Mail-Tester (Email Testing)
- MXToolbox (DNS/Email Testing)
- Klutch.sh Persistent Volumes
- Klutch.sh Deployments
Conclusion
Deploying docker-mailserver on Klutch.sh gives you a complete, production-ready email infrastructure with spam filtering, virus protection, and modern authentication. The combination of docker-mailserver’s comprehensive feature set and Klutch.sh’s container management means you can run enterprise-grade email without the complexity of traditional mail server setups.
With proper DNS configuration, DKIM signing, and spam protection, your mail server will deliver reliably while protecting against common email threats. Whether you’re hosting email for a small team or managing multiple domains, docker-mailserver on Klutch.sh provides the foundation for self-hosted email that you fully control.