0

I have a MySQL database running on an EC2 instance (as opposed to using RDS since this is cheaper). I want to connect to the database in a lambda function, but I keep getting:

(2003, "Can't connect to MySQL server on '' ([Errno 111] Connection refused)")

I have the lambda function on the same VPC and with the same subnet as the EC2 instance (the default VPC) and the security group allows all traffic on all ports. The lambda function has full EC2 access in its permissions. I can verify the MySQL server is up and running and can accept connections from anywhere. I'm totally stumped on what could be causing this issue.

For reference, I'm using PyMySQL to connect:

conn = pymysql.connect(host='<ec2 instance private ip address>', user='<user with all permissions>', passwd='<user password>', db='<database that exists on the MySQL server>', connect_timeout=2)

1
  • Found the problem: I had updated my /etc/mysql/my.cnf file, but there was another file /etc/mysql/mysql.conf.d/mysqld.cnf that had the bind address set to the localhost. Commented Mar 17, 2023 at 6:52

1 Answer 1

1

To allow the AWS Lambda function to connect with your MySQL database running on an Amazon EC2 instance, check the following:

  • The Lambda function is connected to the same VPC as the EC2 instance (Done!)
  • The Security Group of the Lambda function should have the default "Allow All" rules for Outbound traffic
  • The Security Group of the EC2 instance should permit Inbound connections on port 3306 from the Lambda Security Group (or from a wider CIDR range, such as the whole VPC)
  • The NACLs should be left with their default "Allow All" inbound & outbound rules

If that doesn't work, then it sounds like the MySQL server might not be 'listening' to incoming connections from outside the instance. You can test this by launching another EC2 instance in the same VPC and trying to connect to MySQL.

Sign up to request clarification or add additional context in comments.

2 Comments

If it's that the MySQL server isn't listening, how do I fix this? Connecting from another EC2 instance in the same VPC does indeed also get the connection refused.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.