nestjs로 프로젝트 진행 중, mysql2 모듈로 로컬호스트 테스트 중 발생한 에러
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
port: 3306,
database: 'test',
});
위와 같이 연결 시도를 했을 때, 아래와 같은 에러 발생
Error in getDB(): Error: connect ECONNREFUSED ::1:3306
at Object.createConnection (/var/www/example.com/node_modules/mysql2/promise.js:242:31)
at getDB (/var/www/example.com/control/mysqlDB2.js:13:28)
at main (/var/www/example.com/mysql_test2.js:7:33)
at Object.<anonymous> (/var/www/example.com/mysql_test2.js:11:1)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47 {
code: 'ECONNREFUSED',
errno: -111,
sqlState: undefined
}
결과적으로 호스트를 아래와 같이 '127.0.0.1'로 변경해주면 해결됨.
const connection = await mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
port: 3306,
database: 'test',
});
관련해서 mysql2모듈 이슈를 찾아보니, 호스트를 'localhost'라고 기입하면 IPv6로 인식해서 ::1:3306을 못찾는다는 에러를 발생시켰던 것이었다.
와중에 덤으로 socketPath를 직접 지정해버려도 해결은 된다는 점도 배울 수 있었다.
뭔가 다른 근본적인 해결책이 있는건 아니었고, 결과적으로 프로젝트 오너도 그냥 '127.0.0.1'로 쓰거나, ::1로 호스트를 등록해서 쓰라고 한다.
https://github.com/sidorares/node-mysql2/issues/1840
Bug / Feedback: `host:localhost` causes `mysql2` to use `socketPath` · Issue #1840 · sidorares/node-mysql2
Background Context I was setting up mysql2 for the first time and trying to connect to the mysql server installed on my mac. I had trouble connecting to the database and getting a ECONNREFUSED erro...
github.com
https://github.com/sidorares/node-mysql2/issues/1668
node-mysql2 does not work with Node.JS 18.12.1 LTS · Issue #1668 · sidorares/node-mysql2
First, thank you a lot for developing mysql2. I had various node-mysql2 code blocks to connect to MySQL 8 on Ubuntu 20.04 LTS, which worked with Node.js 16 (LTS). None of those code blocks work wit...
github.com