Search code examples
mysqlwordpressamazon-web-servicesdockeramazon-ecs

Connection to RDS MySql from ECS Fargate wordpress container times out


I have a container running (wordpress container if being more specific), which tries to connect to mysql rds instance.

Parameters for the fargate ecs service container:

{ 
    "executionRoleArn": "ignore-this", 
    "containerDefinitions": [ 
        { 
            "name": "MyCoolContainer", 
            "image": "wordpress:latest", 
            "essential": true, 
            "environment": [ 
                {"name": "WORDPRESS_DB_HOST", "value": "host:3306"}, 
                {"name": "WORDPRESS_DB_USER", "value": "user"}, 
                {"name": "WORDPRESS_DB_PASSWORD", "value": "password"}, 
                {"name": "WORDPRESS_DB_NAME", "value": "name"} 
            ], 
            "portMappings": [ 
                { 
                   "hostPort": 80, 
                   "protocol": "tcp", 
                   "containerPort": 80 
                } 
            ], 
            "logConfiguration": { 
                "logDriver": "awslogs", 
                "options": { 
                    "awslogs-group": "/aws/ecs/fargate/prefix", 
                    "awslogs-region": "eu-west-1", 
                    "awslogs-stream-prefix": "prefix" 
                } 
            } 
        } 
    ], 
    "requiresCompatibilities": [ 
        "FARGATE" 
    ], 
    "networkMode": "awsvpc", 
    "cpu": "256", 
    "memory": "512", 
    "family": "wordpress" 
} 

Also, for security groups, I have opened 22, 80, 443, 3306 ports for any IP address.

But the container in ECS still fails to start with the reason:

[17-Sep-2019 08:42:24 UTC] PHP Warning: mysqli::__construct(): (HY000/2002): Connection timed out in Standard input code on line 22

MySQL Connection Error: (2002) Connection timed out

MySQL Connection Error: (2002) Connection timed out

However I can ensure that the RDS instance is accessable, when trying to connect from a local machine with a command:

mysql -uuser -ppassword -hhost -P3306

Also, I can ensure that a (wordpress) container successfuly runs on local machine and successfully connects to a remote RDS database with no timeouts.

EDIT This is how my environment looks like from ECS UI panel: (I have tried to copy paste these values into my local mysql command and it connected successfully.) enter image description here

I suspect there is something wrong with aws services configuration. Any ideas?


Solution

  • Thanks to Adiii and some other articles found on the internet i have a complete solution to this problem.

    You need to simply attach a NAT Gateway to the subnet in which you are launching your ECS Fargate instance.

    Simply launching in a public subnet with an Internet Gateway for some weird reason does not solve the problem (even though logically thinking it should).

    TL;DR:

    NAT Gateway is needed. AWS is f****d up.