Sending emails from Docker using Postfix installed on the Host

In one of our projects, we have multiple Docker images working on a single host. We also use an external email provider (AWS Simple Email Service) to send our emails. Because we don’t want to configure access to SES in each Docker container separately, we configured the local Postfix server on the host itself. If you integrate Postfix with AWS SES, you can find the documentation on the AWS docs.

Once the Postfix is configured to use AWS SES, we will need to:

  • configure Docker images to use Postfix on the host
  • configure Postfix to allow relay from Docker images

First step: determine address of the host, in terms of docker

We need to know the Host’s IP address when working from Docker. You can do this from the docker container (if ip is installed in the image) like this:

> ip route show

default via 172.17.0.1 dev eth0 
172.17.0.0/16 dev eth0  src 172.17.0.7

It shows that the default gateway is 172.17.0.1 which is the host address we are looking for. If you are unable to do this from the Docker container, you can execute this command on the Host:

> ip addr show docker0

3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
  inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0

Again, the Host address in the context of Docker is 172.17.0.1 as you can read in the second line of results.

Second step: configure your application in Docker

Most likely, your application contains some kind of configuration. You must set SMTP to the host’s IP and port to 25. No authentication, no SSL or TLS. This is local delivery.

Third step: allow relay from Docker

By default, Postfix allows the relay of emails from localhost, but it will deny emails coming from Docker. In the Postfix logs (located in /var/log/mail.log you will find: Relay access denied. To make it work, you have to edit the Postfix configuration. Open the /etc/postfix/main.cf file in your favorite editor, locate the mynetworks and add the 172.17.0.0/16 at the end like this:

mynetworks = 127.0.0.0/8 172.17.0.0/16

If there is no mynetworks in your config file, you can create one like the above. Please note that I used only the first two parts of the Host IP address (172.17) followed by 0.0/16. Once the file is adjusted, you have to reload the Postfix service:

> sudo systemctl reload postfix

From now on, your containers should send emails through Postfix on the host.