Running Additional Services with Docker Compose: A Mail Server Example

Abstract: Deploy a functional mail server using Docker Compose with persistent storage, secure port mappings, and antivirus scanning.

Created: 2026-09-17 by
You can deploy a functional mail server using Docker Compose by leveraging the official docker-mailserver image. This approach allows you to define custom container names, hostnames, and port mappings in a single YAML file, ensuring that your email infrastructure is isolated, reproducible, and easy to manage alongside other services on your system.

Prerequisites and Environment Setup

Before writing the configuration file, ensure that your host machine has Docker and Docker Compose installed correctly. If you are running Debian-based systems, version mismatches can sometimes cause issues during installation. It is advisable to verify your current setup against known resolution paths if you encounter startup errors related to binary versions or missing dependencies. You should also have a domain name pointed to your server’s public IP address via DNS records, specifically an A record for the hostname and MX records pointing to that hostname. The docker-mailserver project is designed to be lightweight and modular. It does not require a complex web interface for initial setup but relies on environment variables and volume mounts for persistence. This means all critical data, such as user credentials and mail queues, must be stored in persistent directories on your host machine. Without proper volume mapping, any restart of the container will result in the loss of all configured users and messages.

Defining the Docker Compose Configuration

Create a file named docker-compose.yml in a dedicated directory for your mail server. The core of this setup involves defining a service that uses the mailserver/docker-mailserver image. You need to assign a specific container name and hostname to ensure consistency. For example, setting the container name to mail-server and the hostname to mail.example.com helps with internal networking and log identification. Port mapping is critical for receiving and sending email. You must map the standard SMTP ports: 25 for incoming traffic, 143 for IMAP (unencrypted), 993 for IMAPS (encrypted), 587 for submission (TLS), and 465 for SMTPS. Additionally, exposing port 80 and 443 is often recommended if you plan to use Let's Encrypt for automatic certificate management within the container. Here is a basic structure for the service definition:
version: '3'
services:
  mailserver:
    image: mailserver/docker-mailserver:latest
    container_name: mail-server
    hostname: mail.example.com
    domainname: example.com
    ports:
      - "25:25"
      - "143:143"
      - "587:587"
      - "993:993"
      - "465:465"
    volumes:
      - ./data/mail-data:/var/mail
      - ./data/mail-state:/var/mail-state
      - ./data/mail-logs:/var/log/mail
      - ./data/config:/tmp/docker-mailserver
    environment:
      - ENABLE_POSTFIX=1
      - ENABLE_CLAMAV=1
      - ENABLE_SASLAUTHD=1
    restart: always
In this configuration, the volumes section maps local directories to the container's internal storage paths. The ./data/mail-data directory stores actual email messages, while ./data/config holds runtime configurations. The environment variables enable Postfix for SMTP handling, ClamAV for antivirus scanning, and SASL Auth Daemon for authentication. These settings ensure that the server is ready to handle secure connections and reject spam immediately upon arrival. If you are integrating this mail server with other applications, such as a password manager like Vaultwarden, you may need to adjust network settings to allow inter-container communication. Understanding how containers interact over different networks is essential for maintaining security boundaries while allowing necessary data flow between services.

Initial Setup and User Creation

Once the container is running, you must create email users. The docker-mailserver image provides a helper script for this purpose. You can execute commands directly into the running container using docker exec. To add a new user, run the following command, replacing [email protected] with your desired email address:
docker exec -it mail-server setup email add [email protected]
This command will prompt you to set a password for the new account. It is crucial to use strong passwords, as the server will enforce complexity requirements depending on its configuration. After adding the user, you can verify the creation by listing all existing accounts:
docker exec -it mail-server setup email list
If you encounter issues accessing the mail server from another container, ensure that both containers are on the same Docker network. Network isolation is a key feature of Docker, but it can prevent inter-service communication if not configured explicitly. Referencing guides on accessing mail servers within Docker environments can help troubleshoot connectivity issues that arise after deployment.

Maintaining and Securing the Server

Regular maintenance involves updating the Docker image and checking logs for errors. The docker-mailserver project actively maintains its images, so pulling the latest version ensures you have the most recent security patches. You can update the image by running docker compose pull followed by docker compose up -d. Security best practices include enabling TLS certificates. While the container can generate self-signed certificates for testing, production environments should use Let's Encrypt. The container supports ACME protocols for automatic renewal, reducing the administrative burden of certificate management. Additionally, configuring SPF, DKIM, and DMARC records in your DNS zone is mandatory for delivering emails successfully to major providers like Gmail and Outlook. Without these records, your emails are likely to be marked as spam. Monitoring logs is another vital step. Since logs are mounted to ./data/mail-logs, you can tail them using standard Linux tools to diagnose delivery failures or authentication errors. Keeping an eye on these logs helps identify brute-force attempts or misconfigurations early. For those interested in exploring more complex networking scenarios, such as assigning specific IP ranges to containers using MacVLAN, understanding the underlying network drivers can provide deeper control over your infrastructure. However, for most users, the default bridge network provided by Docker Compose is sufficient for hosting a mail server.

Frequently Asked Questions

How do I reset the password for an existing email user?

You can reset a user's password by executing the setup script inside the container. Use the command docker exec -it mail-server setup email password [email protected] and follow the prompts to enter a new secure password.

Why are my emails going to spam folders?

This is usually caused by missing DNS records. Ensure you have configured SPF, DKIM, and DMARC records correctly for your domain. Without these authentication mechanisms, major email providers will distrust your server's identity.

Can I use this setup with a subdomain like mail.mydomain.com?

Yes, you can use any valid hostname. Just ensure that your DNS MX records point to the subdomain and that the subdomain resolves to your server's IP address. The container's hostname variable should match this fully qualified domain name.

How do I access the webmail interface?

The base docker-mailserver image does not include a webmail client by default. You would typically integrate it with a separate service like RainLoop or SnappyMail, which requires additional configuration in your Docker Compose file to link the two containers.

What happens if I delete the volume data?

Deleting the mapped volumes will permanently erase all stored emails, user accounts, and configuration states. Always backup the ./data directory before performing major updates or migrations to prevent data loss.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More