繁体   English   中英

无法连接到 Node.js 中的 MySQL Docker

[英]Can't connect to MySQL Docker in Node.js

在下面的代码中,我通过 testcontainers 启动了 mysql Docker ,连接到新数据库,并从 SQL 目录填充数据库。 但是,每次我运行 function 时,我都会收到一条错误消息,指出服务器已关闭连接。 我究竟做错了什么?

// Spin up a MySQL docker and populate it according to the files in the sql directory

import fs from 'fs'
import path from 'path'
import { createPool } from 'mysql2/promise'
import { GenericContainer, Wait } from 'testcontainers'
const sqlDir = `${__dirname}/../sql`
export const mysqlContainer = async () => {
  const container = await new GenericContainer('mysql', '5.7')
    .withExposedPorts(3306)
    .withEnv('MYSQL_ALLOW_EMPTY_PASSWORD', '1')
    .withEnv('MYSQL_DATABASE', 'testdb')
    .withWaitStrategy(Wait.forLogMessage('mysqld: ready for connections.'))
    .start()
  console.log('Container started')
  return container
}

export const setupDatabases = async (container) => {
  const connection = await createPool({ host: 'localhost', user: 'root', password: '', port: container.getMappedPort(3306) })
  console.log('Connected to database')
  const dir = await fs.promises.opendir(sqlDir)
  for await (const dirent of dir) {
    console.log(dirent.name)
    if (dirent.name.match(/\.sql$/)) {
      const fileContents = await fs.promises.readFile(path.join(sqlDir, dirent.name))
      await connection.query(fileContents.toString())
      console.log(`process SQL file ${dirent.name}`)
    }
  }
}

https://github.com/testcontainers/testcontainers-node/issues/73

原来.withWaitStrategy(Wait.forLogMessage('mysqld: ready for connections.'))导致 MySQL 服务器在启动后立即关闭。

此外,我需要使用container.getContainerIpAddress()而不是localhost作为主机。

更新草图:

const { createPool } = require('mysql2/promise')
const { GenericContainer, Wait } = require('testcontainers')
const mysqlContainer = async () => {
  const container = await new GenericContainer('mysql', '5.7')
    .withExposedPorts(3306)
    .withEnv('MYSQL_ALLOW_EMPTY_PASSWORD', '1')
    .withEnv('MYSQL_DATABASE', 'testdb')
    .start()
  console.log('Container started')
  return container
}

(async () => {
  const container = await mysqlContainer()
  try {
    const connection = await createPool({ host: container.getContainerIpAddress(), user: 'root', password: '', port: container.getMappedPort(3306) })
    console.log('Connected to database')
    console.log(await (connection.query('SELECT count(*) FROM information_schema.columns')))
  } catch (e) {
    console.error(e, e.stack)
  }
  await container.stop()
})()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM