[英]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.