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
O. Jones
99.6k17 gold badges118 silver badges167 bronze badges
asked Jan 18, 2014 at 16:35
2
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.
answered Oct 20, 2014 at 12:42
Victor DodonVictor Dodon
1,7563 gold badges18 silver badges27 bronze badges
6
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
answered Jan 18, 2014 at 16:54
Pez CuckowPez Cuckow
13.9k16 gold badges80 silver badges130 bronze badges
5
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
JoSSte
2,7585 gold badges31 silver badges49 bronze badges
answered Feb 7, 2017 at 4:05
wunowuno
9,39117 gold badges90 silver badges177 bronze badges
0
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.
Obsidian Age
40.6k10 gold badges47 silver badges70 bronze badges
answered May 17, 2017 at 22:45
1
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 runningmysql -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 withGRANT 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"
});
answered Jun 12, 2019 at 19:20
chick3n0x07CCchick3n0x07CC
6481 gold badge9 silver badges27 bronze badges
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');
});
answered Jan 16 at 22:23
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
answered Jan 26, 2021 at 21:29
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.
Anton Krug
1,5072 gold badges18 silver badges32 bronze badges
answered May 5, 2021 at 2:43
Hi,
I have an error like below. while i initiate my server it was working smoothly after the certain period of time it has been raised.for connectivity i used the file like below. for resolve this issue i googled and tried so many suggestions no one it works fine. when i restart my server then it was
fine for another certain period of time. for deployment here am using appache for reverse proxy and pm2 for load balancing.
nodemysql connectivity
- dbconfig.js
const mysql = require("mysql"); const logger = require("../log4js"); const dbConfig = { connectionLimit: 10, host: 'localhost', user: 'root', password: 'test', database: 'test' }; let pool = mysql.createPool(dbConfig); // Ping database to check for common exception errors. pool.getConnection((err, connection) => { if (err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.error('Database connection was closed.') } if (err.code === 'ER_CON_COUNT_ERROR') { console.error('Database has too many connections.') } if (err.code === 'ECONNREFUSED') { console.error('Database connection was refused.') } } if (connection){ connection.release(); return; } }) module.exports = pool
database.js
const pool = require('./dbconfig'); const logger = require('../log4js'); function executeQuery(sql, callback) { pool.query(sql, function (error, results, fields) { logger('INFO',sql); if (error) { logger('INFO',error); return callback(error, null); }else{ logger('INFO',results); return callback(null, results); } }); } function query(sql, callback) { executeQuery(sql,function(err, data) { if(err) { return callback(err,null); }else{ return callback(null, data); } }); } module.exports = { query: query }
sample issue
[2019-09-13T11:14:02.078] [INFO] bussiness_logic - select id, name, username, password, allowedoperator, status from user where id = "1" and status = "ACTIVE"
[2019-09-13T11:14:02.078] [INFO] bussiness_logic - { Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
--------------------
at Protocol._enqueue (/var/www/fms/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/var/www/fms/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/var/www/fms/node_modules/mysql/lib/Connection.js:119:18)
at Pool.getConnection (/var/www/fms/node_modules/mysql/lib/Pool.js:48:16)
at Pool.query (/var/www/fms/node_modules/mysql/lib/Pool.js:202:8)
at executeQuery (/var/www/fms/database/database.js:5:10)
at Object.query (/var/www/fms/database/database.js:18:5)
at UserProfile.FnGetUserProfile (/var/www/fms/classes/userprofile.js:13:25)
at Object.<anonymous> (/var/www/fms/cron/test.js:15:13)
at Module._compile (internal/modules/cjs/loader.js:778:30)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true }
Firstly i was a windows programmer and recently switched to linux (ubuntu 18.04 distro) .
On Windows my code was working fine but on linux it started showing the error.Error: connect ECONNREFUSED 127.0.0.1:3306
my connection code :
import { createConnection } from 'mysql';
export default createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'rent_compair',
});
server.js:
import express from 'express';
import cors from 'cors';
import admin from './routes/admin';
import db from './config/mysql';
const app = express();
db.connect((err) => {
if (err) throw err;
console.log('Db Connected!');
});
app.use(cors());
app.use(express.json());
app.use('/', admin);
app.listen(process.env.PORT || 5000, console.log('Server Connected!'));
xampp started with sudo privileges:
xampp server snap
asked Sep 6, 2020 at 11:42
The reason for this is that you cannot connect to MySQL with the root
account anymore. This rule was changed — and enforced — within MySQL starting a few years ago. While it is possible to update the configuration to allow it, it is strongly discouraged even for development environments.
Instead, if you need the application to have complete control over a database, you can create an account and give it full control like this:
CREATE USER 'app_name'@'localhost' IDENTIFIED WITH mysql_native_password BY 'superSecretPassword!123';
GRANT ALL ON `database`.* TO 'app_name'@'localhost';
In the event you want the application to have even more control, you can allow it access to everything, including the ability to create new accounts, like this:
GRANT ALL ON *.* TO 'app_name'@'localhost' WITH GRANT OPTION;
answered May 16, 2021 at 6:21
matigomatigo
17.8k6 gold badges35 silver badges61 bronze badges
Содержание
- Как решить? «ECONNREFUSED — connection refused by server»
- Первый Метод. Изменение Дефолтного Значения Порта FileZilla
- Второй Метод. Отключение Антивируса/Брандмауэра
- Третий Метод. Изменение Мастера Настройки Сети FileZilla
- Выводы
- Node.js Error: connect ECONNREFUSED — how to connect Node with phpMyAdmin
- The solution:
- Final thoughts
- Error: connect ECONNREFUSED #874
- Comments
- Footer
- connect ECONNREFUSED 127.0.0.1:3306 for my node application #2268
- Comments
- This comment has been minimized.
- This comment has been minimized.
- Footer
- How to Fix ECONNREFUSED – connection refused by server Error
- How to Fix SSH Connection Refused Error Video Guide
- Method 1 – Disabling Firewall/Anti-Virus Software on Your Computer
- Method 2- Changing FileZilla’s Default Port Value
- Method 3 – Editing FileZilla’s Network Configuration Wizard
- Further Reading About FTP
- Conclusion
Как решить? «ECONNREFUSED — connection refused by server»
Вы тоже столкнулись с ошибкой ECONNREFUSED — connection refused by server в FileZilla? Тогда здорово, что вы нашли это руководство. Я покажу вам три метода, как можно исправить эту ошибку FTP.
Первый Метод. Изменение Дефолтного Значения Порта FileZilla
Причиной ошибки может быть неправильный порт при подключении через FileZilla. В этой ситуации вам просто нужно изменить порт FTP по умолчанию на дефолтный номер порта SFTP. Просто измените 21 на 22 в поле ввода “Port”.
Второй Метод. Отключение Антивируса/Брандмауэра
Иногда эта ошибка может возникать, когда антивирусное программное обеспечение и/или брандмауэр отказывает FileZilla в попытках установить соединение.
В случае, если антивирус или брандмауэр вызывает ECONNREFUSED, вам нужно просто отключить это ПО, а затем снова подключиться. Сначала я покажу вам, как это сделать в macOS:
- Нажмите на иконку “Apple” в верхнем меню. Перейдите в “System Preferences”.
- Найдите раздел настроек “Security & Privacy”.
Перейдите во вкладку “Firewall” и выберите “Turn Off Firewall”.
Если вы используете Windows, выполните следующие действия:
- В строке поиска по Windows введите запрос “Control Panel”.
- Затем перейдите в раздел “System & Security” и найдите “Windows Defender Firewall”.
В меню слева найдите “Turn Windows Defender Firewall on or off”.
Подробней о том, как деактивировать разное антивирусное программное обеспечение можно прочитать здесь (англ).
Если отключение антивируса или брандмауэра не помогло и вы по-прежнему получаете ошибку «ECONNREFUSED — connection refused by server», попробуйте следующий метод.
Третий Метод. Изменение Мастера Настройки Сети FileZilla
Что делать, если предыдущие решения не принесли желаемого результата? Чтобы исправить ошибку, вы также можете попробовать изменить конфигурации сети FileZilla:
- Подключитесь к FTP-клиенту FileZilla, затем перейдите в “Edit” и выберите “Network Configuration Wizard”.
На этом этапе вам необходимо убедиться, что все настройки были выполнены правильно. Нажмите кнопку “Test”, чтобы FileZilla попыталась установить соединение с probe.filezilla-project.org. Программа выполнит несколько простых тестов.
Если тестирование пройдет без сбоев, попробуйте снова подключиться к вашей учетной записи хостинга. В этот раз все должно работать отлично. Если же ошибка ECONNREFUSED все равно не исчезла, обратитесь в службу поддержки вашего хостинга.
Выводы
Вот и все. Это и есть три метода, как исправить ошибку «ECONNREFUSED — connection refused by server». Надеемся, что один из них таки поможет вам решить проблему с FileZilla. Если у вас остались вопросы или вы знаете другие решения, не стесняйтесь оставить комментарий!
Источник
Node.js Error: connect ECONNREFUSED — how to connect Node with phpMyAdmin
I spend more than 6 hours searching and testing, I get frustrated, angry and you know. just for 3 minutes job.
Here it’s my success story with incredible persistant Node.js error connect ECONNREFUSED .
Day 1.
I run this code, and should work fine.
Oh, but no, some errors
Usual errors, maybe 3-4 minutes. I changed host: ‘localhost’ to host : ‘127.0.0.1’, port: 8080, or maybe 8000, oh yes, 3306 this is. No, not that. Oh, yes, hostname: ‘127.0.0.1:3306’. No. Adding database, remove database. Change every thing I can now change. Nothing.
«You should check if your XAMMP server is running», yes it is green.
Maybe it is the port 8443. node app.js enter, connect ECONNREFUSED. no, it’s not the port. No password, no root, no port. What can solve this?
OOhh, yes, I know, I should thinking about that. Maybe I need to put the project in root XAMPP root folder. No.
connect ECONNREFUSED
3 hours later. I need more music.
Day 2
Today, Sunday, with some first snow outside, I discovered something new. There is an IP address on my XAMPP, and maybe this is how I can solve the error.
Unfortunately it was not the case.
Starting to find the real solution in my case
And after I read Yannick Motton’s best answer on post host-xxx-xx-xxx-xxx-is-not-allowed-to-connect-to-this-mysql-server I found the solution.
The solution:
1. Create an user with password, and grant all provileges
CREATE USER ‘username’@’localhost’ IDENTIFIED BY ‘password’;
GRANT ALL PRIVILEGES ON . TO ‘username’@’localhost’ WITH GRANT OPTION;
CREATE USER ‘username’@’%’ IDENTIFIED BY ‘password’;
GRANT ALL PRIVILEGES ON . TO ‘username’@’%’ WITH GRANT OPTION;
FLUSH PRIVILEGES;
This will set user: username and pass: password
2. Change localhost with your XAMPP IP (and also add username/password for user and password)
Change host: «localhost» to host:»192.168.64.2″, and update with user: «username», password: «password».
node app + enter
Connection established It’s done. Hooray.
3. Celebrate the victory
Now that your terminal print Connection established, you whould celebrate the victory with dev friends.
Final thoughts
Hope this article will help you to solve the connect ECONNREFUSED error and to connect Node.js with phpMyAdmin in just a few minutes.
“Patience, persistence, and perspiration make an unbeatable combination for success.” — Napoleon Hill
Источник
Error: connect ECONNREFUSED #874
Error: connect ECONNREFUSED is the error I get everything I try to connect to a mysql database using this code:
The complete error output is:
This time is installed using:
so the version is not specified.
The text was updated successfully, but these errors were encountered:
It is because your connection was refused trying to establish a TCP connection to port 3306 on localhost. The following is the mysql command you can use to verify connectivity (you must run it exactly as specified here):
Your MySQL server is likely not setup to listen on a TCP socket, so you probably want to check your MySQL server configuration.
oh thanks, this still getting me error.
ERROR 2003 (HY000): Can’t connect to MySQL server on ‘localhost’ (61)
But at least I know it is a mysql thing in my end.
oh thanks, this still getting me error.
Right, I figured it would still give you an error, because the error is just a bad configuration of the MySQL server. I just wanted to illustrate it is not an issue with this library.
You can always connect to your MySQL server using a UNIX socket instead of TCP, though. Run the following command on the server:
Then take the value it gave you ( /tmp/mysql.sock in this example) and give it to the socketPath option for this module:
Perfect! Thanks @dougwilson 👍
it’s weird, but also the solution is to uncheck on MAMP the option Allow local access only .
So to make myself sure of it, I removed the socketPath option /Applications/MAMP/tmp/mysql/mysql.sock ) and still get connection.
But I’d stick with your solution seems like the right one.
Thanks @dougwilson everything it’s working now.
I get the same err,it toke me half day to google,thank for all this answers.
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
connect ECONNREFUSED 127.0.0.1:3306 for my node application #2268
Hi,
I have an error like below. while i initiate my server it was working smoothly after the certain period of time it has been raised.for connectivity i used the file like below. for resolve this issue i googled and tried so many suggestions no one it works fine. when i restart my server then it was
fine for another certain period of time. for deployment here am using appache for reverse proxy and pm2 for load balancing.
nodemysql connectivity
The text was updated successfully, but these errors were encountered:
The error ECONNREFUSED 127.0.0.1:3306 is being raised by Node.js itself, and not this module. This module passes the error through, though, from Node.js. Basically, this module is asking Node.js to create a TCP connection to 127.0.0.1 , port 3306 , but for whatever reason, Node.js cannot do this and raises the ECONNREFUSED error.
Unfortunately there is nothing this module can do to resolve this.
It could be an issue with Node.js (in which you can open on the Node.js issue tracker) or an issue with your MySQL server (did it restart or something?). If there is some specific things you can list to change in this module, we can re-open the issue, though.
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
How to Fix ECONNREFUSED – connection refused by server Error
If you come across the ECONNREFUSED – connection refused by a server error in FileZilla and don’t know how to fix it, then you’re in the right place. This tutorial will show you how to resolve the FTP error through a few methods. Let’s check it out!
Error code | ECONNREFUSED |
Error type | FTP |
Error variations | Connection attempt failed with “econnrefused – connection refused by server”. Error: connect econnrefused |
Error causes | Firewall configurations Anti-virus configurations Using incorrect port Incorrect Filezilla configurations |
How to Fix SSH Connection Refused Error Video Guide
Learn how to fix the SSH Connection Refused error using three simple methods in this video tutorial.
Method 1 – Disabling Firewall/Anti-Virus Software on Your Computer
One of the possible reasons for this error is that the firewall and anti-virus software on your computer is preventing FileZilla from making a connection.
If that’s the cause of the Error: Connect econnrefused – connection refused by server error, simply disable the firewall and anti-virus software on your computer and try to reconnect. Here’s how to do so on Windows:
- Press the Windows key on your keyboard and type in Control Panel.
- Head to System and Security and locate Windows Defender Firewall.
- On the left menu bar, find the option to Turn Windows Defender Firewall on or off.
- On the next window, modify the settings to turn off Windows Defender Firewall for public and private networks, then press Ok.
On macOS, you need to:
- Click on the Apple menu on the upper left toolbar, then System Preferences.
- Locate the Security & Privacy option.
- Switch to Firewall and click on the Turn Off Firewall option.
To disable different anti-virus software on your computers, check out this article for detailed guidance.
That’s it! This method should fix the ECONNREFUSED – connection refused by server error instantly if your computers’ firewall and anti-virus are the problems. Should it persists, turn everything back on and do the next method instead.
Method 2- Changing FileZilla’s Default Port Value
Sometimes, the error happens because you’re using the wrong port when connecting with FileZilla. If that’s the case, all you need to do is put 22 (default SFTP port) instead of 21 (default FTP port number) on the port column, as seen below.
Important! Make sure to edit the Site Manager’s configuration and change the protocol to SFTP – SSH File Transfer Protocol if you’re using port 22.
Method 3 – Editing FileZilla’s Network Configuration Wizard
If none of the solutions above work, try editing FileZilla’s network configurations to fix the ECONNREFUSED – connection refused by server error. To access the Network Configuration Manager, here’s what you need to do:
- Connect to FileZilla FTP client and head to Edit ->Network Configuration Wizard.
- Press Next to proceed once a Firewall and router configuration wizard window pop out.
- Choose Passive (recommended) as the Default transfer mode, and put a check on the Allow fallback to another transfer mode on failure option.
- Select Use the server’s external IP address instead.
- Choose the Get the external IP address from the following URL. If the input field is blank, enter the default value, which is http://ip.filezilla-project.org/ip.php, and proceed.
- Don’t make any changes to the port range configuration and select Ask operating system for a port.
Now you just need to make sure everything is configured correctly. Click on the Test button, and FileZilla will try to connect to probe.filezilla-project.org to perform some simple tests.
If you don’t receive any errors during the test, try connecting to your hosting account again, and you should connect just fine. If the ECONNREFUSED – connection refused by server error still appears, contact your hosting customer support team for assistance.
Further Reading About FTP
Conclusion
By finishing this short tutorial, you’ve learned how to fix the FileZilla Error: Connect econnrefused – connection refused by server error through three simple methods. Here’s a quick recap of the reasons why it happens and how to fix it:
- Computers’ anti-virus software and firewall preventing FileZilla from making a connection – turn them off temporarily on your computers.
- Using the wrong port when making a connection – Use SFTP default number port (22) instead of the FTP port (21)
- Misconfiguration in your FileZilla Client – editing the configurations through FileZilla’s Network Configurations Wizard.
Simple, right? If you have any other solutions, or if you have any questions, do let us know in the comments!
Edvinas is a professional mentor and trainer of customer support agents. When he’s not teaching the secrets of providing exceptional service, he likes to travel the world and play basketball.
Источник