Search code examples
amazon-web-servicessmtpamazon-ecsconnection-timeout

Why am I getting time out errors when sending emails from Amazon ECS container?


I have a Spring Boot API which has a service to send emails. This service works when I'm running the app locally or with a simple docker-compose inside an EC2 instance. However when I moved the app to Amazon ECS, it stopped working.

The error:

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: email-smtp.us-east-
1.amazonaws.com, 587; timeout -1;

My application.yml (mail section):

spring:
    mail:
    host: ${MAIL_HOST}
    port: ${MAIL_PORT:587}
    username: ${MAIL_USER}
    password: ${MAIL_PASSWORD}
    properties:
      mail:
        smtp:
          auth: true
          starttls.enable: true

I've already tried to open the tcp port 587 in my security group, but it didn't work too.

More info about ECS:
I'm using ECS with EC2 launch type and an Application Load Balancer sitting in front of it.


Solution

  • Figured it out!

    The formula to the problem:

    problem = (ECS with EC2 launch type) + (Task definition with awsvpc network mode) + (public subnet) + (not reading the AWS manual)^999   
    

    As stated in the Running a Task Using the EC2 Launch Type Guide

    Only private subnets are supported for the awsvpc network mode. Because tasks do not receive public IP addresses, a NAT gateway is required for outbound internet access, and inbound internet traffic should be routed through a load balancer.

    To deal with the problem I updated my task definition to use bridge network mode.

    Ps: I'm not concerned about running multiple containers in the same instance though.