在下面的代码中,我将通过testcontainers启动mysql Docker ,连接到新数据库,并从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}`)
}
}
}
参见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()
})()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句