'MySQL default_socket_timeout timeout only when connecting from ECS Fargate Task

This is a strange one. In my ECS Fargate task, I have a Docker container running PHP code that calls mysqli_connect to connect to an RDS MySQL database. Works great.

However, sometimes I want to stop the RDS database to save money which will cause the mysqli_connect command to fail.

Sample code:

<?php
    $connection = mysqli_connect($hostname, $username, $password, $database);

    echo "done";
?>

When I run this from a container in my local environment connecting to a stopped local MySQL database via host.docker.internal, it fails immediately and code continues to execute, which is what I want.

(Corrected) When I run this from a container in my local environment connecting to the SAME stopped RDS MySQL database, it waits for the PHP default_socket_timeout value (default 60 seconds) then fails and code continues to execute. I want it to fail immediately.

When I run this from a container in my Fargate task, it waits for the PHP default_socket_timeout value (default 60 seconds) then fails and code continues to execute. I want it to fail immediately.

I realize I can set the default_socket_timeout to 1 second. I've done that and seen it fail after 1 second instead of 60, but why is this the only scenario where default_socket_timeout is invoked?

UPDATE: I figured out part of the cause and it has to do with the AWS RDS instance. When it's running and I purposely make the value of $hostname, $username, $password, or $database wrong, it will fail immediately. Only when I stop the RDS instance will it wait for default_socket_timeout seconds no matter if the code is running in a Fargate task container or local container.

My solution was to avoid the default_socket_timeout delay entirely by calling the AWS describe-db-instances API periodically to get its status before calling mysqli_connect().



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source