node-mysql error: connect ECONNREFUSED - mysql

I'm trying to setup a remote connection between my database server and a client node app using node-mysql.
When I try to connect to the remote db, I get this error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect ECONNREFUSED
at errnoException (net.js:646:11)
at Object.afterConnect [as oncomplete] (net.js:637:18)
Connecting to a local db works ok (with the socketPort parameter).
I can connect to this remote db with PHP from my computer localhost as well as another server I own so I don't think there's something wrong with mysql conf.
For info, nodejs is running with nginx and I've setup a proxy to make node work on port 80, maybe this is the issue?
How can I check that?
Thanks.
EDIT
Here's my code, just in case:
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
debug: false,
host: '12.34.56.67',
user: 'user',
password: 'pass'
});

Try using mysql socket:
var connection = mysql.createConnection({
user: 'user',
password: 'pass',
socketPath: 'mysql-socket-path', /*example: /Applications/MAMP/tmp/mysql/mysql.sock*/
database: 'dbname'
});

Should one still look for an answer:
Check your MySql server's configuration.
In my case running netstat -ln | grep mysql(as per Troubleshooting Problems Connecting to MySQL) revealed that my server is listening on the socket /tmp/mysql.sock so in createConnection's options I used socketPath: '/tmp/mysql.sock' instead of host: and port:

This error has to do with the MySQL client not being able to connect to the host:port given. As defined in errno.h, ECONNREFUSED is an error that is thrown when a connection is refused - this is possibly caused by:
a firewall such as iptables blocking the port
no such process running on the port
the process is running on a different host
the host or port were incorrect
In my case, my MySQL server was not correctly bound to 0.0.0.0 for external connections, instead being bound to 127.0.0.1, as it is by default; however you can change this.
The error does not originate from the node-mysql package, as doubly shown by the stacktrace, which only shows errors from net.js.

I added port:3306, that solved the issue .
var connection = mysql.createConnection
({
user: 'root',
password: 'root',
server: 'localhost',
port:3306,
database: 'abcd',
insecureAuth: true,
dialect: 'mysql',
multipleStatements: true,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
connection.connect();

Ok so I checked with node-mysql dev and it seems that it's not a node-mysql bug, but it was hard to investigate more.
Anyway, I found this lib which works, so I'll go with it.
https://github.com/mariano/node-db-mysql

i had the same problem.
solved it, by set the right port in the createConnection function options.
get your port by using following command:
netstat -tlnp
search for program name mysqld or just named.

Use the command: yarn run start, and DO NOT use: cd /folderX && yarn run start

Related

NodeJS xdevapi - Creating Connection to MySQL Database

I've been using the official MySQL NPM package found here: https://www.npmjs.com/package/#mysql/xdevapi.
However, I can't seem to make a connection to the server. Here's the current error message I get:
Error: The server connection is not using the X Protocol.
Make sure you are connecting to the correct port and using a MySQL 5.7.12 (or higher) server intance.
Here is the code that generates that issue:
const db = mysqlx.getSession('root#localhost:33060/schemaname').then(session => {
console.log('SESSION STARTED!!');
});
This is just a test database without a password so I don't think the password is the issue. Also, I've made sure I'm using the right port and the MySQL version is 8.x.x so I don't think that is the issue. I created a database using the app Dbngin and I verified I could connect to the database by running the following command in my terminal: mysql -u root -h 127.0.0.1 --port=33060 -p which worked. I'm also running this on my Mac.
Update:
I've also tried passing a config object without much luck:
const config = {
user: 'root',
password: '',
host: 'localhost',
port: 33060,
schema: 'schemaname'
};
const db = mysqlx.getSession(config).then(session => {
console.log('SESSION STARTED!!');
});
Unfortunately, this code produces the same error above.
I tried it out myself and got the same error because you are using the wrong port. It could be you changed the default port, but the default port is: 3306 and not 33060 although I have to use port 33060 while my port is 3306.
X-protocal requires you to multiply your port by 10 I see here: https://dev.mysql.com/doc/mysql-port-reference/en/mysql-ports-reference-tables.html. So if your original port is 33060 I guess it should be 330600.
You could try this command SHOW VARIABLES LIKE 'mysqlx_port';

How do I establish MYSQL connection to AWS ec2 instance from local machine?

I'm finished with my project and I'm trying to deploy it to AWS. I have an ec2 instance as my webserver with the following configuration details:
NodeJS using port 5000
PM2 (keeping server alive at all times)
NGINX as web server reading from my build file
MySQL within ec2 instance as my database. (using port 3306)
My problem is I'm having trouble establishing a connection from my local machine to my AWS ec2 instance that has the MYSQL db inside of it. I opened up MYSQL workbench and I can connect to it just fine there but when I try and establish a connection string to the DB from node.js it gives me an error.
I was able to successfully connect to the DB within MYSQL workbench but how can I connect to it now from nodejs connection string?
What I already tried was the following:
1) In AWS security group opening up TCP Rule for all incoming traffic at port 5000
2) In AWS security group opening up MYSQL/Aurora Rule for all incoming traffic at port 3306
3) Granting all privileges on . to user and flushing and restarting mysql server.
Error it gives me in the console.
`{ Error: connect ECONNREFUSED 14.54.xxx.xx:3306
at Object._errnoException (util.js:1019:11)
at _exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1175:14)
--------------------
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '14.54.xxx.xxx',
port: 3306,
fatal: true }`
Here is my code trying to establish the connection:
```var mysql = require("mysql");
// Local Works just fine
// var connection = mysql.createConnection({
// host: "localhost",
// user: "root",
// password: "xxx",
// database: "devdb",
// charset: "utf8mb4"
// });
// Production Connection to AWS MYSQL instance (stuck on)
var connection = mysql.createConnection({
host: "14.54.xxx.xxx",
port: "3306",
user: "jordan",
password: "xxx",
database: "productiondb"
charset: "utf8mb4"
});
// Test the db connection
connection.connect(function(err) {
if (err) {
console.log(err);
} else {
console.log("Connected!");
}
});
module.exports = connection;
```
I expect to be able to successfully connect to the db instance from my NodeJS
Make sure again, I think your security groups have something wrong, maybe your server listening internally so It's happening. Go your EC2 security group and select Inbound and add rules as type=mysql, proto=tcp, port range=3306, source=0.0.0.0/0,::/0 (allow all)
There are a couple of reasons due to which this might be happening -
Configure MySQL database
#start MySQL server sudo service mysqld start
#run configuration sudo mysql_secure_installation
In the prompt, follow the following steps:
Enter current password for the root account: press Enter key
Set root password? Y
New password: yourpassword
Re-enter new password: yourpassword
Remove anonymous users? Y
Disallow root login remotely? n
Remove test database and access to it? Y
Reload privilege tables now? Y
If you are using RDS then you will have to provide NAT access to the VPC which holds your database. For more info please refer here
Actually I think I just figured it out.
So the default mysql configuration file has the ip binded to 127.0.0.1. However, I changed the binding to my ec2 public ip and also changed the default "mysql" to "jordan" and I saved the configuration file, restarted the mysql service and it now works.
Thank you for the suggestions I'll write this down in my documentation to check for in the future.

Node.js MySQL - Error: connect ECONNREFUSED

I use Node.js server side. I tried my code on localhost and everything works fine. I bought a server and installed Apache and node.js on it and test my web application there. I correctly changed the MySQL connection configurations from localhost to the server configurations.
I test my web application with this configuration:
var mysql = require('mysql');
var mysqlConnection;
function new_mysqlConnection() {
mysqlConnection = mysql.createConnection({
host : 'myurl.at',
user : 'myusername',
database : 'mydatabase',
password : 'mypassword'
});
}
I start the node.js server with:
$ node server.js
When I load the page, it's correctly displayed, but when Node.js try to connect to the database I always got the following error:
Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
--------------------
at Protocol._enqueue (/var/www/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/var/www/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/var/www/node_modules/mysql/lib/Connection.js:119:18)
at reconnectDb (/var/www/server.js:319:18)
at app.get.email (/var/www/server.js:109:2)
at Layer.handle [as handle_request] (/var/www/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/node_modules/express/lib/router/index.js:302:13)
at /var/www/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/node_modules/express/lib/router/index.js:261:10)
You need to add the value of socket path to the config object:
socketPath: '/var/run/mysqld/mysqld.sock'
In MAMP, you go to http://localhost:8888/MAMP, and you find:
/Applications/MAMP/tmp/mysql/mysql.sock
At the end you have:
var connection = mysql.createConnection({
host : config.host,
user : config.user,
password : config.pass,
database : config.db,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
I was having same problem but I solved this by changed
host: 'localhost'
to
host: '127.0.0.1'
Check for your MySQL port in your server.
In MAMP, by default it uses 8889.
Add that to your connection config.
Your MySQL config should look like this.
this.pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'root',
database: 'todo',
port: '8889'
});
Check your xampp server mysql is running or not
I fix it by the following code after a struggle of two days. ( Just giving my solution, you might have another solution as well.)
Follow these steps as well.
Delete all node_modules
Run "npm audit --force"
install npm packages by "npm install"
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock"
});
Note: I am using sequelize with graphql (NODEJS).
if using using express and MySQL. port should be same as your MySQL port.
The default MySQL port is 3306.
let defaultPORT = 3306;
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'yourMYSQLUser',
password : 'yourMYSQLPassword'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var server = app.listen( defaultPORT, function() {
console.log( defaultPORT)
});
I would recommend to add the port in the below table of yours;
const pool=mysql.createPool({
host: '127.0.0.1',
user: 'root',
database: 'node-complete',
port: "3307",
password: 'Aditya2000#'
});
The port number is to be taken from your MySql Workbench from the homepage table of it which should shows:
Local Instance MySql root localhost: 3307 -> this localhost number
has to be written there.
In most cases, your host should match your bind-address in the MySQL config file.
if your bind-address is 0.0.0.0 or 127.0.0.1 then setting host to 'localhost' should work. but if your bind-address is your actual IP address then you should add your IP address instead.
var sql_con = mysql.createConnection({
host: "ip address",// should be the same as bind-address
user: "jeffery",
password: "damnthing",
database: "KOKATOOO"
});
I had the same issue turns out mysql was not running.
Make sure it's running by:
$ systemctl status mysqld
If you see this:
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Tue 2020-08-18 12:12:29 CDT; 32min ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 18668 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS (code=exited, status=2)
Process: 18650 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 18668 (code=exited, status=2)
Status: "SERVER_BOOTING"
Then the service is not running, to run enter:
$ systemctl start mysqld
I Also have same problem in google cloud with nginx
changed
host: 'localhost'
to
host : 'cloud_instance_private_ip'
may help some one with same problem
It's probably course from the absence of port and database.
first I wrote:
host,
user,
password and no database and port.
Here you need to specified what is your database name, what is your port number.
So the total must be:
1. host
2. user
3. password
4. database
5. port
It's works for me, try it if it works for you too.
I 'm also have same problem but i found the solution by adding:
port:"80"
I connect with node.js to the server php mysql using this code:
var mysql=require('mysql');`
var connection=mysql.createConnection({
port:"80",
host:"localhost",
user:"root",
password:""
});
open services from the search bar.In there search for MySQL80.Right click on it and click on start.Now run the code.It should work.Most of the times the SQL service is inactive when the computer starts up
have experienced a similar issue where with the same configs, could connect from local -> mysql server but not when deployed as cronjob to k8s cluster. Not sure why but workaround was to add sleep 10 && before running application: args: ["-c", 'sleep 10 && node index.js']
I had same issues, and i resolved it by adding my port
Port: YOUR_PORT
had this same issue and I solved it by adding the port
I created a new user in PhpMyAdmin with a username as "user" and password as "". I set the host as "%" which allows connection from any host.
Use the IP address you find in the XAMPP control panel as the host in the node js code
I have used the IP address in the XAMPP control panel as the host in the database connection
This solved the problem and connected to the database
Maybe it will help someone, In my case I am using strapi app when I encountered this issue, I realized that I did not create database, So I am using Mamp I go to php my admin created db and updated database.js in config folder and now its working fine
In my case it was working locally, but now when deployed.
The problem was I hadn't updated the environment variables
I am facing the same problem but I have done that:
Turn ON your MySQL using XAMPP
Create a database that will mention in the code. (I have 'node js' named database.
By doing these, my code is worked perfectly.
You can see here

errorError: getaddrinfo ENOTFOUND - mysql

I'm running a server on c9.io using Node.js and trying to connect to Mysql
I guess I get this error:
Error: getaddrinfo ENOTFOUND
because the connection to the db is wrong.
I'm using this:
var connection = mysql.createConnection({
host: "REMOTE_ADDR",
user: "MYUSERNAME", // this is replaced by my username
database: "c9",
port: 3306
});
Any idea what's wrong?
Thanks!
After one hour, and I don't know why, I found the issue.
In my case I replaced
host: 'localhost'
by
host: '127.0.0.1'
I know it's been a while since this was asked but I spent the better part of today trying to fix this. What to check for:
Within your nodejs source:
Try it without the 'port' option unless on your db VM, MySQL is
listening on a port besides 3306. I had this option specified but had
connection problems until I removed it. And 3306 is already the
default value for the option anyway.
Try it with the actual host IP in the host 'option'. I was using an actual domain name and, more often than not, node-mysql would throw
the same exact "errorError: getaddrinfo ENOTFOUND" When I used the IP
address, no more errors. Also, I did not get this error while on
Ubuntu instances in AWS. As soon as I switched over to Ubuntu VMs in
Azure, I got the problem.
Set the "debug" connection option to true which will give you a verbose trace of what's happening during the connection
On your db VM/Box/Instance:
Ensure that MySQL is listening on the right port
If you're seeing the error when trying to make concurrent connections using a pool, check that your max_connections and max_user_connections haven't been changed from the default settings in my.conf
Monitor "SHOW PROCESSLIST;" in MySQL to see if you see any issues there
This code works for me.
var mysql = require('mysql');
var con = mysql.createConnection({
host: '127.0.0.1',
port: '3306',
user: 'yourUsername',
password: '**********'
});
con.connect(function(err){
if(err) throw err;
console.log('connected!');
});
the host and port name find them in your mysql server.
in-place of '127.0.0.1' you can use 'localhost'
I was facing this issue. I did fix it simply you have to change your configuration of a connection string like if you are running on local machine try
host:'localhost' or host:'127.0.0.1'
...and set your user name and if you want this to publish your code on server then give the host according to server if in docker container give it name host:'db'.
I almost spend two hours to understand what is the problem with the mysql database. I am using Windows cmd.
I tried multiple ways e.g
npm install mysql2
Changing localhost to 127.0.0.1
Refreshing node
so in order to resolve this issue
[Error: getaddrinfo ENOTFOUND 127.0.0.1:3306]
I open XAMPP and start the MySQL database then manually check the credentials and works fine for me.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'test',
password: 'test123',
});

How to tell node.js that mysql is not running on default port?

I'm having a problem similar to this person's: connect ECONNREFUSED - node js , sql
I'm trying to connect app.js to an existing database running as part of MAMP. MAMP runs mysql on port 8889; how do I tell node.js which port to find mysql on?
When you are initializing the mysql client, along with username and password, you can pass a different value for port.
const client = mysql.createClient({
user: '??',
password: '??',
port: 8889
});
For those initializing the mysql connection object using mysql.createPool({...}), it's the same solution as the accepted answer. For Reference
const connection = mysql.createPool({
host: ...,
port: 8889,
user: ...,
password: ...,
});