Не удается подключиться к MySQL Docker в Node.js - PullRequest
0 голосов
/ 28 апреля 2020

В приведенном ниже коде я запускаю mysql Docker с помощью testcontainers , подключаюсь к новой базе данных и заполняю базу данных из каталога SQL. Однако каждый раз, когда я запускаю эту функцию, я получаю сообщение о том, что сервер закрыл соединение. Что я делаю неправильно?

// 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}`)
    }
  }
}

1 Ответ

0 голосов
/ 30 апреля 2020

См. 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()
})()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...