Skip to content

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
└── .dockerignore

Creating the Dockerfile

Create a Dockerfile for your mail server:

FROM docker.io/mailserver/docker-mailserver:latest
# Copy configuration
COPY config/ /tmp/docker-mailserver/
# Copy initialization script
COPY setup/init.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/init.sh
# Create directories
RUN mkdir -p /var/mail /var/mail-state /var/log/mail
# Expose mail ports
# SMTP
EXPOSE 25
# ESMTP with STARTTLS
EXPOSE 587
# ESMTP over TLS
EXPOSE 465
# IMAP
EXPOSE 143
# IMAP over TLS
EXPOSE 993
# POP3
EXPOSE 110
# POP3 over TLS
EXPOSE 995
# Health check
HEALTHCHECK --interval=60s --timeout=30s --start-period=120s --retries=3 \
CMD supervisorctl status || exit 1
# Environment variables with defaults
ENV ENABLE_SPAMASSASSIN=1
ENV ENABLE_CLAMAV=1
ENV ENABLE_FAIL2BAN=1
ENV ENABLE_POSTGREY=0
ENV ONE_DIR=1
ENV DMS_DEBUG=0
ENV POSTFIX_MESSAGE_SIZE_LIMIT=52428800
ENV ENABLE_AMAVIS=1
# Use supervisor entrypoint from base image

Creating 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 restrictions
smtpd_helo_required = yes
smtpd_helo_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_helo_hostname,
reject_non_fqdn_helo_hostname
# Sender restrictions
smtpd_sender_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_sender,
reject_unknown_sender_domain
# Relay restrictions
smtpd_relay_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
defer_unauth_destination

Creating 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 exist
mkdir -p /var/mail
mkdir -p /var/mail-state
mkdir -p /var/log/mail
mkdir -p /tmp/docker-mailserver
# Set permissions
chown -R 5000:5000 /var/mail
chmod 755 /var/mail
echo "Initialization complete."

Creating the .dockerignore File

Create a .dockerignore file:

.git
.github
*.md
LICENSE
.gitignore
.DS_Store

Deploying docker-mailserver on Klutch.sh

Follow these steps to deploy your mail server:

    Plan Your DNS Configuration

    Before deployment, plan the DNS records you’ll need:

    Record TypeNameValue
    AmailYour server IP
    MX@mail.example.com (priority 10)
    TXT@v=spf1 mx -all
    TXT_dmarcv=DMARC1; p=quarantine; rua=mailto:postmaster@example.com
    TXTmail._domainkey(DKIM public key - generated after setup)

    Push Your Repository to GitHub

    Initialize and push your configuration:

    Terminal window
    git init
    git add .
    git commit -m "Initial docker-mailserver configuration"
    git remote add origin https://github.com/yourusername/mailserver-deploy.git
    git push -u origin main

    Create 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:

    • 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 Environment Variables

    Configure the following environment variables:

    VariableValue
    HOSTNAMEmail.example.com
    DOMAINNAMEexample.com
    ENABLE_SPAMASSASSIN1
    ENABLE_CLAMAV1
    ENABLE_FAIL2BAN1
    SSL_TYPEletsencrypt
    POSTMASTER_ADDRESSpostmaster@example.com
    PERMIT_DOCKERnone

    Attach Persistent Volumes

    Add persistent volumes for mail storage:

    Mount PathRecommended SizePurpose
    /var/mail100+ GBUser mailboxes
    /var/mail-state10 GBService state and databases
    /var/log/mail5 GBMail server logs
    /tmp/docker-mailserver1 GBConfiguration 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:

    1. Set MX record pointing to your mail server
    2. Configure SPF record
    3. Set up DMARC policy

    Generate DKIM Keys

    After the container is running, generate DKIM keys:

    Terminal window
    # Access container
    setup config dkim

    Add the generated public key to your DNS as a TXT record.

    Add Email Accounts

    Create your first email account:

    Terminal window
    setup email add user@example.com

    Test Your Configuration

    Send test emails to verify:

    • Outbound email delivery
    • Inbound email receipt
    • Spam filtering
    • DKIM signing

Managing Email Accounts

Adding Users

Add new email accounts using the setup script:

Terminal window
setup email add user@example.com

You’ll be prompted for a password, or generate one:

Terminal window
setup email add user@example.com "$(openssl rand -base64 16)"

Updating Passwords

Change user passwords:

Terminal window
setup email update user@example.com

Removing Users

Delete email accounts:

Terminal window
setup email del user@example.com

Setting Quotas

Configure mailbox size limits:

Terminal window
setup quota set user@example.com 5G

Creating Aliases

Set up email aliases:

Terminal window
setup alias add alias@example.com target@example.com

Multi-Domain Configuration

Adding Domains

docker-mailserver supports multiple domains:

  1. Add MX record for the new domain
  2. Configure SPF, DKIM, and DMARC
  3. Add user accounts for the new domain

Per-Domain DKIM

Generate DKIM keys for each domain:

Terminal window
setup config dkim domain example.com
setup config dkim domain example.org

Domain-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=letsencrypt

Manual Certificates:

SSL_TYPE=manual
SSL_CERT_PATH=/path/to/fullchain.pem
SSL_KEY_PATH=/path/to/privkey.pem

SPF Records

Configure SPF to authorize your mail server:

v=spf1 mx a:mail.example.com -all

Options:

  • +all: Allow all (not recommended)
  • ~all: Soft fail
  • -all: Hard fail (recommended)

DKIM Configuration

DKIM signs outgoing mail:

  1. Generate keys with setup config dkim
  2. Add public key to DNS
  3. Verify with online DKIM testers

DMARC Policy

Configure DMARC for authentication policy:

v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100

Policy options:

  • p=none: Monitor only
  • p=quarantine: Mark as spam
  • p=reject: Reject unauthenticated mail

Spam and Virus Protection

SpamAssassin Configuration

SpamAssassin scores incoming mail:

ScoreTypical Action
< 5.0Deliver normally
5.0-10.0Mark as spam
> 10.0Reject

Custom rules in /etc/spamassassin/local.cf:

# Whitelist specific senders
whitelist_from trusted@example.com
# Blacklist domains
blacklist_from *@spamdomain.com
# Adjust scores
score RULE_NAME 0.0

ClamAV Updates

ClamAV virus definitions update automatically. Monitor logs for update status.

Fail2Ban Rules

Fail2Ban protects against brute-force attacks:

# Check banned IPs
fail2ban-client status postfix-sasl
# Unban an IP
fail2ban-client set postfix-sasl unbanip 1.2.3.4

Monitoring and Logs

Viewing Logs

Access mail server logs:

Terminal window
# All mail logs
tail -f /var/log/mail/mail.log
# Postfix specific
tail -f /var/log/mail/postfix.log
# Dovecot specific
tail -f /var/log/mail/dovecot.log

Queue Management

Monitor and manage the mail queue:

Terminal window
# View queue
postqueue -p
# Flush queue
postqueue -f
# Delete specific message
postsuper -d MESSAGE_ID
# Delete all queued mail
postsuper -d ALL

Service Status

Check component status:

Terminal window
supervisorctl status

Production 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:

  1. Mail storage (/var/mail)
  2. Configuration and state (/var/mail-state)
  3. Custom configurations
  4. 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

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.