6

I have an instance on AWS and MySQL database working on it. I was able to connect to the instance via workbench on my local machine. However, I am not able to connect to the database via the node js code. Below is the snippet :

var express    = require("express");
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'ec2-52-33-41-xxx.us-west-2.compute.amazonaws.com',
 port      :  3306,
  user     : 'ec2-user',
  password : 'root',
  database : 'FAMILY_GIVING_TREE'

});
var app = express();

connection.connect(function(err){

if(!err) {
    console.log("Database is connected ... ");    
} else {
    console.log("Error connecting database ... ");    
}
});

THE ERROR is :

{ [Error: connect ECONNREFUSED 52.33.xx.84:3306]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '52.33.41.84',
  port: 3306,
  fatal: true }

The node js code is w=not written over the AWS instance, I am writing it on my machine and yes the port 3306 is enabled in security groups.

I get the database connection issue. Any idea where am I going wrong? Thanks in advance.

5
  • 1
    What is the error? console.log(err) Commented Jul 10, 2016 at 3:44
  • Is the NodeJS code running on the same server as the database? If not you will need to open port 3306 in the Security Group. Commented Jul 10, 2016 at 3:46
  • I am not using MongoDB @MarkB Commented Jul 10, 2016 at 5:04
  • can you try port: 3306 -> port: '3306'. Commented Jul 10, 2016 at 9:44
  • Is there a way to avoid adding the mysql dependency.. does AWS-native not have a something like mysql-client that I could just require without adding the package (and allt he other things that would then require). You have to reduce your sizes as far as possible for APIs running serverless Commented Jun 3, 2020 at 12:05

2 Answers 2

4

There is a syntax error in your node.js code. Replace port : 3306, with below you are missing the ''

port : '3306',
Sign up to request clarification or add additional context in comments.

Comments

2

First, you must do the settings, that make Mysql accessible remotely.

https://mariolurig.com/coding/connect-remotely-mysql-database-amazon-ec2-server/

Second, in my case, I had to use my ec2 public IP address instead of public DNS. So:

var connection = mysql.createConnection({
  host     : '52.33.41.xx',
 port      :  '3306',
  user     : 'remote',
  password : 'password',
  database : 'FAMILY_GIVING_TREE'

});

Third, keep in mind that 'remote' is the user you grant all privilege on your DB for localhost and '%' (from all IP ). GoodLuck

Comments

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.