I am currently containerizing a legacy PHP application that relies heavily on the native Sendmail binary for triggering system notifications. I’ve managed to install the package, but the service fails to route mail correctly, or it hangs indefinitely during the container startup process. How should I properly configure the /etc/hosts file or the Sendmail macro files within a Dockerfile to ensure fast mail delivery without compromising container portability or security?
3 answers
Configuring Sendmail in Docker is notoriously tricky because Sendmail expects a fully qualified domain name (FQDN) and a stable hostname, which Docker containers lack by default. To fix the "hanging" issue, you must ensure your container's ID is mapped to 127.0.0.1 in /etc/hosts. In your Dockerfile, you should install sendmail and sendmail-cf, then use m4 to regenerate the sendmail.cf file after modifying sendmail.mc. It is often easier to use a simplified relay like ssmtp or msmtp if you just need to forward mail to an external SMTP server, as Sendmail's footprint is quite heavy for a microservice architecture.
Does your application specifically require the Sendmail binary, or are you open to using a dedicated Mail Transfer Agent (MTA) container like Postfix or a mock server like MailHog for development? Often, debugging Sendmail logs inside a container is difficult because the syslog service isn't running by default. Have you checked if your base image has the necessary libraries to handle local mail queuing?
The most common fix for the Sendmail delay in Docker is running line=$(head -n 1 /etc/hosts | getsubopt) ; echo "$line localhost.localdomain localhost $(hostname)" > /etc/hosts right before starting the service.
I agree with Patricia. That specific /etc/hosts hack is a lifesaver. Without it, Sendmail spends several minutes trying to resolve the container's internal hash-based hostname, which usually results in a timeout before any mail is actually sent.
Kevin, that's a valid point regarding logging. To answer your question, if someone must use Sendmail, they should redirect logs to STDOUT so Docker can capture them. You can do this by adding O LogLevel=9 to your configuration. However, for most modern use cases, I’d suggest shifting to a simple SMTP client library within the application code instead of relying on a local system binary. It makes the container much smaller, more secure, and significantly easier to maintain across different cloud environments.