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

Node.js通过Knex连接Docker MySQL容器出现ECONNREFUSED错误

解决Docker中Node.js(Knex)无法连接MySQL容器的ECONNREFUSED问题

问题详情

报错信息:

{
    "errno": -111,
    "code": "ECONNREFUSED",
    "syscall": "connect",
    "address": "127.0.0.1",
    "port": 3306,
    "fatal": true
}

Docker Compose配置:

version: "3.8"
services: 
  app:
    build: 
      context: .
      dockerfile: Dockerfile
    ports: 
      - 3000:3000
    volumes: 
      - .:/app
      - /app/node_modules
  
  mysql_server:
    image: mysql:8.0
    ports:
      - 3307:3306
    environment: 
      - MYSQL_DATABASE=transaction_app
      - MYSQL_ROOT_PASSWORD=root

Knex连接代码:

const db= knex ({
  client: 'mysql2',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    user: 'root',
    password: '',
    database: 'transaction_app'
  }
});

解决步骤

  • 修正数据库连接地址
    Docker Compose默认会创建专属网络,容器之间通过服务名而非127.0.0.1通信——127.0.0.1在app容器内指向自身,而非MySQL容器。需将Knex配置中的host改为mysql_server(对应docker-compose里的MySQL服务名)。

  • 修正数据库密码
    Docker Compose中设置的MYSQL_ROOT_PASSWORD为root,但Knex配置里的password是空字符串,需同步改为'root'。

  • 确认端口配置
    容器内部MySQL使用默认3306端口,主机映射的3307端口是给外部工具连接用的,app容器连接时直接用3306端口即可,无需修改。

修改后的Knex连接代码

const db= knex ({
  client: 'mysql2',
  connection: {
    host: 'mysql_server',
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'transaction_app'
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:20:32