You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js连接MySQL报ECONNREFUSED错误求助

WSL Ubuntu 20.04中Node连接localhost:3306 MySQL失败(ECONNREFUSED)

问题描述

在WSL Ubuntu 20.04环境中运行Node服务器,尝试连接localhost:3306的MySQL时,持续收到Error: connect ECONNREFUSED 127.0.0.1:3306错误。已确认MySQL服务运行正常、用户权限配置正确、密码无误,且本地已创建测试表,但问题仍未解决。

错误日志

[nodemon] starting `node server.js`
Server running on port 3000
Error: connect ECONNREFUSED 127.0.0.1:3306
    at PromisePool.execute (/mnt/d/learn_NodeJS/nodejs_intro/node_modules/mysql2/promise.js:374:22)
    at Object.<anonymous> (/mnt/d/learn_NodeJS/nodejs_intro/server.js:27:4)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49 {
  code: 'ECONNREFUSED',
  errno: -111,
  sql: undefined,
  sqlState: undefined,
  sqlMessage: undefined
}

已尝试操作

创建新MySQL用户并授权:

mysql> CREATE USER 'xaliz'@'localhost' IDENTIFIED WITH mysql_native_password BY 'xaliz0605';
Query OK, 0 rows affected (0.01 sec)
 
mysql> GRANT ALL ON `database`.* TO 'xaliz'@'localhost';
Query OK, 0 rows affected (0.01 sec)

配置文件

database.js

const mysql = require('mysql2');
 
const pool = mysql.createPool({
  host: 'localhost',
  user: 'xaliz',
  database: 'node-complete',
  password: 'xaliz0605',
  port: 3306,
});
 
module.exports = pool.promise();

server.js

const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
 
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const errorController = require('./controllers/error');
 
const db = require('./utils/database');
const app = express();
const port = 3000;
 
app.set('view engine', 'ejs');
app.set('views', 'views');
 
db.execute('SELECT * FROM products')
  .then((result) => {
    console.log(result);
  })
  .catch((err) => {
    console.log(err);
  });
 
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
 
app.use('/admin', adminRoutes);
app.use(shopRoutes);
 
// 404 Error Catch-All Middleware
app.use(errorController.get404);
 
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

解决方案

1. 区分MySQL运行环境(WSL vs Windows主机)

  • 如果MySQL安装在Windows主机:WSL的localhost并非指向Windows的localhost,需替换为Windows的实际IP地址。

    • 在WSL终端执行cat /etc/resolv.conf,复制nameserver后的IP(通常是Windows的网关地址);或在Windows命令行执行ipconfig,找到以太网适配器WSL的IPv4地址。
    • 修改database.js中的host字段为该IP。
  • 如果MySQL安装在WSL内部:确保MySQL允许外部连接,修改配置文件:

    • 编辑MySQL配置文件(路径通常为/etc/mysql/mysql.conf.d/mysqld.cnf),将bind-address的值改为0.0.0.0。
    • 重启MySQL服务:sudo service mysql restart。

2. 修正用户授权范围

  • 之前授权的用户仅允许localhost连接,若使用WindowsIP或其他地址连接,需重新授权:
    -- 允许所有地址连接该用户
    CREATE USER 'xaliz'@'%' IDENTIFIED WITH mysql_native_password BY 'xaliz0605';
    -- 授权对应数据库(注意替换为实际使用的node-complete)
    GRANT ALL ON `node-complete`.* TO 'xaliz'@'%';
    -- 刷新权限
    FLUSH PRIVILEGES;
    
  • 注意:原授权命令中使用的是database.*,但实际代码连接的是node-complete数据库,需保证授权的数据库名称与代码一致。

3. 检查防火墙设置

  • 如果MySQL在Windows:确保Windows防火墙允许3306端口的入站连接。
  • 如果MySQL在WSL:执行sudo ufw allow 3306开放3306端口,再执行sudo ufw enable启用防火墙(若未启用)。

内容的提问来源于stack exchange,提问作者TigerDriver03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:22:52