Error when connecting mysql instance with nodejs

Asked

Viewed 1,326 times

2

I raised with Docker mysql container

docker run --name mysql-docker -e MYSQL_ROOT_PASSWORD=password -d -p 3306:3306 mysql

But when trying to connect via Node

node index.js

the following error occurs

    { Error: connect ECONNREFUSED 127.0.0.1:3306
    at Object._errnoException (util.js:992:11)
    at _exceptionWithHostPort (util.js:1014:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
    --------------------
    at Protocol._enqueue (DIRETORIO DO PROJETO\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Protocol.handshake (DIRETORIO DO PROJETO\node_modules\mysql\lib\protocol\Protocol.js:51:23)
    at Connection.connect (DIRETORIO DO PROJETO\node_modules\mysql\lib\Connection.js:118:18)
    at Object.<anonymous> (DIRETORIO DO PROJETO\api\index.js:13:12)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3306,
  fatal: true }

index.js file

const mysql = require('mysql');    
const connection = mysql.createConnection({
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: 'password',
});
  • You released port 3306 on the Docker, but connected to the 3307? Why?

  • I changed the file. I will change the post.

2 answers

0

Port that you will use for your application access -> 3307:3306 <- port that the container opened internally, use port 3307 in the connection of your application.

const connection = mysql.createConnection({
  host: 'localhost',
  port: 3307,
  user: 'root',
  password: 'password',
});

Or:

const connection = mysql.createConnection({
  host: 'mysql-docker',
  port: 3307,
  user: 'root',
  password: 'password',
});

0

Use the name of your Docker container as a host in case I understand that Voce named your container with "mysql-Docker", if you have any doubts about the name execute "Docker ps -a" and check the container name

const mysql = require('mysql');    
const connection = mysql.createConnection({

  host: 'mysql-docker',

  port: 3306,

  user: 'root',

  password: 'password',

});
  • With container name not working too

Browser other questions tagged

You are not signed in. Login or sign up in order to post.