node.js mysql error: ECONNREFUSED - mysql

Why can't I connect to the mysql server?
On the same server an Apache/PHP server is running and it connects without problems!?
var mysql_link = {
host : 'localhost',
port : 3308,
database: 'nodetest',
user : 'root',
password : 'xxx'
};
var connection = mysql.createConnection(mysql_link);
connection.connect(function(err){
console.log(err);
if(err != null){
response.write('Error connecting to mysql:' + err+'\n');
}
});
connection.end();
error
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
fatal: true }
update
root#dyntest-amd-6000-8gb /var/www/node/dyntest # ps ax | grep mysqld
7928 pts/0 S+ 0:00 grep mysqld
28942 ? S 0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid
29800 ? Sl 17:31 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/var/lib/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/var/lib/mysql/mysql-error.log --open-files-limit=65535 --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306

I know this question has been answered, but for me the problem was that the mysql server listens on a Unix socket not on a tcp socket. So the solution was to add:
port: '/var/run/mysqld/mysqld.sock'
to the connection options.

If this has worked before, my first guess would be that you've already got a copy of your node.js script running in the background which is holding the connection.
I believe connection refused is a tcp/ip error message, rather than something from MySQL which suggests that it is either not running or is running on another port or with sockets.
Could you try telnet'ing to port 3308? To see if the server is running on that port?
telnet localhost 3308
Can you also try:
mysql -hlocalhost -uroot -pxxx

Overview
For anyone else having this problem and is running mamp. I suspected the problem had to do with the network and not MySQL or Node.js.
Solution
If you open MAMP and click MySQL in the left navigation panel it will pull up the MySQL options page. In the center of the page you will see a checkbox that says,
"Allow network access to MySQL".
Check this box and then restart your MAMP. At this point you can now test your connection to MySQL with telnet or a node.js script.
Hint
Remember you can check which port your MySQL is running on by opening MAMP and clicking the ports link on the left navigation panel.
Visual Aid

For some very odd reason, my computer only allowed me to have port 3306 as default port for my connection in order for it to work.

Mac OS on M1 MacBook Pro here with MySQL installation via brew:
Changing the host from 'localhost' to '127.0.0.1' and creating a different user with a password solved this issue for me.
For some reason I cannot connect to my DB with root user and no password.
I created the new user on MySQL Workbench, but you can create a new user with admin privileges via the mysql CLI also.
Just google it.
This is how my backend looks:
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3500;
const db = mysql.createConnection({
host: '127.0.0.1',
user: 'admin',
password: 'admin',
});
db.connect((err) => {
if (err) throw err;
console.log('connected to database');
});
app.listen(port, () => {
console.log('server listening on port 3500');
});

I wanted to comment my solution here, just in case there were people as newbie as me in databases.
I was getting this error because I had installed the mysql NPM package correctly but I hadn't installed any implementation of MySQL on my computer (I didn't know I had to).
I'm using Arch Linux so, in my case, with the NPM package already installed in my project, I did pacman -Syu mariadb (MariaDB is the default implementation of MySQL in Arch Linux) and then configured it following the guide.
Then, you can use the root user you just configured or create a new one to use in your project. For the latter:
Enter mysql CLI by running mysql -u root -p.
Enter the password for root user.
Create a new database with CREATE DATABASE mydatabase;.
Create a new user with CREATE USER test IDENTIFIED BY "testpass";.
Grant privileges to test user to use your new database with GRANT ALL PRIVILEGES ON mydatabase.* TO test#localhost IDENTIFIED BY "testpass";. See for more information on this.
And then, in my project, I would have:
let connection = mysql.createConnection({
host: "localhost",
user: "test",
password: "testpass",
database: "mydatabase"
});

If you are using MAMP please note that mysql default db_port is set to 8889 so you for this purpose I had to change it to 3306 (or whatever your app mysql db_port is set to).
My issue was that node server was connecting using port 3306, so it was giving the error below then crashing but mysql was up and seemed to establishing a connection through localhost, although I couldnt test it because node server was down.
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
Once I changed the port on MAMP mysql from 8889 to 3306, node server established connection through port 3000 and giving the statement below:
server running on port 3000
The solution is: 2

I use Windows 10 and I have Windows Subsystem For Linux (WSFL). I can execute my project from the WSFL console, but my MySQL is installed in Windows and they can not connect, however when I execute my project from a Windows console then it works without any problems.

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 connect to MySQL using node.js (with node-mysql driver)?

I have the following code, which I am trying to run. I have given comments accordingly to mention what all I have tried.
// File saved as app.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'localhost', //even tried with 127.0.0.1
port:3306, //confirmed port by looking into /etc/mysql/my.cnf has [client] port = 3306
user:'root', //credentials are verified since Php My Admin logs in with same
password:'password' //credentials are verified since Php My Admin logs in with same
//Even tried to connect using _socket: '/var/run/mysqld/mysqld.sock'
});
connection.connect(function(err) {
// connected! (unless `err` is set)
if(err)
console.log(err); return;
});
Since the default port is not changed, the phpMyAdmin is working fine for me. But I am not able to connect using node-mysql driver from Node.js.
The following is the error message I am getting:
amolkulkarni#ubuntu:~/Project/Node_MySQL$ node app.js
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
fatal: true }
Could anyone please help on this?
Update: Based on comments
amolkulkarni#ubuntu:~/ ps ax | grep mysqld
5905 ? S 0:00 sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking
5906 ? Sl 0:12 /usr/sbin/mysqld --skip-grant-tables --skip-networking
28964 ? Ssl 0:00 /usr/sbin/mysqld
29098 pts/3 S+ 0:00 grep --color=auto mysqld
I am able to connect to mysql using mysql -hlocalhost -uroot -ppassword but if I replace with ip e.g. mysql -h192.168.1.10 -uroot -ppassword It gives error as follows:
ERROR 2003 (HY000): Can't connect to MySQL server on '192.168.3.78' (111)
Your server is started with --skip-networking flag:
Do not listen for TCP/IP connections at all. All interaction with
mysqld must be made using named pipes or shared memory (on Windows) or
Unix socket files (on Unix). This option is highly recommended for
systems where only local clients are permitted.
Try to connect to unix socket or start server with TCP enabled.