Setup Mailhog inside Docker through Postfix (Ubuntu 18.04 LTS)

November 28, 2018
This will make sure all mails sent from your server are catched by Mailhog, and not delivered in the real world.

This is recommended for your dev and test servers.

Yesterday I had to set up Mailhog on one of our docker test servers, so we won't accidentally send emails to anyone. Plus we get a nice, simple web UI.
However, I ran into a problem I couldn't find an answer to anywhere; the default_transport should be set to smtp in /etc/postfix/main.cf, or else the mails won't be sent to Mailhog. This probably was because I installed postfix as "Local only".

So, I decided to make a complete tutorial.

Requirements

Setup Mailhog inside Docker

Create a new folder and add this docker-compose.yml file

version: '3'

services:
  mailhog:
    image: mailhog/mailhog
    container_name: mailhog
    restart: always
    ports:
      - "1025:1025" # SMTP
      - "8025:8025" # Web UI

Run docker-compose up -d

See the web UI works at http://localhost:8025 (or http://[your-server-ip]:8025).

Setup Postfix

Postfix is needed so all mails are forwarded to Mailhog, including the host's sendmail.

Install postfix

sudo apt install postfix
  1. Select "Internet Site"
  2. Use the default name and press Enter

Edit /etc/postfix/main.cf

relayhost = 127.0.0.1:1025
default_transport = smtp

Reload postfix for the changes to take effect: sudo postfix reload

Test

echo "Test mail" | mail -s "It works!" you@domain.tld

You should see the email in your web UI at http://localhost:8025

Debugging

If you need to debug you can always sudo tail -f /var/log/mail.log for the postfix log.
And for mailhog you can use sudo docker-compose logs -f

Follow RSS/Atom Feed
See more posts