docker nodejs容器无法从本地主机连接到mysql容器

时间:2018-07-04 15:40:01

标签: node.js docker

我在计算机上运行nodejs docker和mysql。但是,即使我提供了正确的用户名和密码,我也无法通过本地主机访问数据库。 当我尝试访问docker nodejs服务器时,我收到错误消息。

这是$ docker-compose logs -f记录我尝试通过localhost访问docker服务器时收到的消息:

db_1            | App listening on port 9000
backend_1       | Error occurred: { Error: connect ECONNREFUSED 
172.18.0.3:3306
backend_1       |     at Object.createConnection 
(/opt/app/node_modules/mysql2/promise.js:31:31)
backend_1       |     at _callee$ (/opt/app/src/index.js:29:30)
backend_1       |     at tryCatch (/opt/app/node_modules/regenerator- 
runtime/runtime.js:65:40)
backend_1       |     at Generator.invoke [as _invoke] 
(/opt/app/node_modules/regenerator-runtime/runtime.js:303:22)
backend_1       |     at Generator.prototype.(anonymous function) [as 
next] (/opt/app/node_modules/regenerator-runtime/runtime.js:117:21)
backend_1       |     at step (/opt/app/src/index.js:21:191)
backend_1       |     at /opt/app/src/index.js:21:437
backend_1       |     at new Promise (<anonymous>)
backend_1       |     at /opt/app/src/index.js:21:99
backend_1       |     at /opt/app/src/index.js:26:1
backend_1       |   message: 'connect ECONNREFUSED 172.18.0.3:3306',
backend_1       |   code: 'ECONNREFUSED',
backend_1       |   errno: 'ECONNREFUSED',
backend_1       |   sqlState: undefined }
backend_1       | 
backend_1       |   Error: connect ECONNREFUSED 172.18.0.3:3306
backend_1       |       at Object.createConnection 
(/opt/app/node_modules/mysql2/promise.js:31:31)
backend_1       |       at _callee$ (/opt/app/src/index.js:29:30)
backend_1       |       at tryCatch 
(/opt/app/node_modules/regenerator-runtime/runtime.js:65:40)
backend_1       |       at Generator.invoke [as _invoke] 
(/opt/app/node_modules/regenerator-runtime/runtime.js:303:22)
backend_1       |       at Generator.prototype.(anonymous function) 
[as next] (/opt/app/node_modules/regenerator- 
runtime/runtime.js:117:21)
backend_1       |       at step (/opt/app/src/index.js:21:191)
backend_1       |       at /opt/app/src/index.js:21:437
backend_1       |       at new Promise (<anonymous>)
backend_1       |       at /opt/app/src/index.js:21:99
backend_1       |       at /opt/app/src/index.js:26:1

这是我的docker-compose.yml文件:

version: '3'
services:
  backend:
    build:
      context: ./
      dockerfile: .dockerfiles/BackendDev
    ports:
      - "9000:9000"
    volumes:
      - ./backend:/opt/app
    restart: always
  backend_test:
    build:
      context: ./
      dockerfile: .dockerfiles/BackendDev
    command: yarn run test:watch
    ports:
      - "9005:9005"
    volumes:
      - ./backend:/opt/app
    restart: always
  db:
    image: mysql:8.0.3
    volumes:
      - /var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: db_rootpass
      MYSQL_DATABASE: db_1
    restart: always
  mywebsql:
    image: quantumobject/docker-mywebsql
    ports:
      - "9001:80"
    restart: always
我试图将端口号更改为3306,但没有帮助。 有什么我想念的吗?

这是我的js文件:

import 'babel-polyfill';
import Koa from 'koa';
import Router from 'koa-router';
import mysql from 'mysql2/promise';

// The port that this server will run on, defaults to 9000
const port = process.env.PORT || 9000;

// Instantiate a Koa server
const app = new Koa();

// Instantiate routers
const test = new Router();

// Define API path
const apiPath = '/api/v1';

const connectionSettings = {
  host: 'db',
  user: 'root',
  database: 'db_1',
  password: 'db_rootpass',
  namedPlaceholders: true,
};

test.get(`${apiPath}/test`, async (ctx) => {
  // Tell the HTTP response that it contains JSON data encoded in UTF-8
  try {
    const conn = await mysql.createConnection(connectionSettings);
    const [data] = await conn.execute(`
      SELECT *
      FROM test_table
      `);

    console.log('Data fetched:', data);

    // Tell the HTTP response that it contains JSON data encoded in UTF-8
    ctx.type = 'application/json; charset=utf-8';

    // Add stuff to response body
    ctx.body = { greeting: 'Hello world!', data };
  } catch (error) {
    console.error('Error occurred:', error);
    ctx.throw(500, error);
  }
});

app.use(test.routes());
app.use(test.allowedMethods());

// Start the server and keep listening on port until stopped
app.listen(port);

console.log(`App listening on port ${port}`);

1 个答案:

答案 0 :(得分:1)

出于调试目的,您还可以直接连接到Docker容器,例如:docker exec -it CONTAINER_ID /bin/bash,然后尝试在那里本地连接到mysql DB。我首先要验证数据库是否能够接受连接。此外,您确定在您的nodeJS应用尝试连接数据库时数据库已经在运行吗?我没有对docker compose做任何事情,因此我不确定网络功能,但是当您使用network_mode: host时,我认为您也应该能够直接从您的主机连接到mysql容器带有mysql-client的本地计算机。您应该先进行这些测试。
给我们一些反馈:)