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)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
crayon123
  • 3
  • 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. – crayon123 Mar 17 '23 at 06:52

1 Answers1

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.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • 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. – crayon123 Mar 17 '23 at 01:13
  • This might be relevant: [Connect to mysql on Amazon EC2 from a remote server](https://stackoverflow.com/q/9766014/174777) – John Rotenstein Mar 17 '23 at 02:49