Node Mysql connection refused Errors: ECONNREFUSED, ETIMEDOUT, ENOENT

Publish date: 2024-06-13

I created an application that takes input from an HTML form and inserts it into a MySQL Database. Everything was working perfectly until I started playing with Docker, SSH and NGINX for my study projects.

Here's my database.js file:

const mysql = require('mysql2'); const con = mysql.createConnection({ host: 'localhost', user: 'myusername', password: 'password', database: 'mydb', port: 3000, socketPath: '/var/run/mysqld/mysqld.sock' }); con.connect(function(err) { if (err) throw err; console.log('Database connected!'); }); module.exports = con; 

Now, whenever I run the server with

nodemon index.js 

Server starts just fine but I get the database.js error:

 database.js:13 if (err) throw err; ^ Error: connect ENOENT /var/run/mysqld/mysqld.sock at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) 

If I remove the pathSocket, I get the following error:

database.js:12 if (err) throw err; ^ Error: connect ECONNREFUSED 127.0.0.1:3000 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) 

And if I remove the port, the following error shows up:

database.js:11 if (err) throw err; ^ Error: connect ECONNREFUSED 127.0.0.1:3306 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) 

I looked everywhere on the Internet and tried everything, I even uninstalled the Ubuntu distribution (I'm using Win 10 with WSL 2) and reinstalled it. But the problem persists.

--

I believe it's a problem with the ports and so but I'm new to this networking fuss and I really don't know what to do.

2 Answers

Use sudo find / -type s for search your socketPath, maybe the path is wrong

The error Error: connect ENOENT /var/run/mysqld/mysqld.sock is referring to your file's location. ENOENT means no such a file or directory.

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmluYWaBdYQ%3D