Using system postfix as mail relay for docker containers

Posted by Markus Benning on August 16, 2017
Updated on 26. July 2018:

Systemd startup may even fail when postfix is started after docker because the docker unit returns after the process has been started. At this point the docker bridge is not yet setup.

If you configured postfix as a local MTA it will only listen on local network devices. To make it accessible from your docker container add the docker0 interface to inet_interfaces in main.cf:

inet_interfaces = 127.0.0.1, [::1], 172.17.0.1

Since the docker interface is started when the docker service starts you have to make sure docker is started before postfix. With systemd you can do this by creating the file /etc/systemd/system/postfix.service.d/after-docker.conf with the content:

[Unit]
After=docker.service

Because the docker network bridge may not yet be ready at system bootup postfix may fail to start because it cannot bind to that address.

A possible solution is to allow processes to bind to “non-local” (not existing locally) addresses by setting the net.ipv4.ip_nonlocal_bind sysctl option:

sysctl net.ipv4.ip_nonlocal_bind=1

To make this setting permanent:

echo "net.ipv4.ip_nonlocal_bind = 1" > /etc/sysctl.d/postfix-docker.conf

If you want to send outgoing mails with a destination other than the local system you can allow this by adding the docker subnet to mynetworks in main.cf:

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 172.17.0.1/16