nodejs가 marida db에 연결할 수 없습니다.명령줄을 통해 연결 가능
DB에 연결할 때 다음 오류가 발생합니다.
node_server_1 | Error connecting to database: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10002ms
node_server_1 | (pool connections: active=0 idle=0 limit=10)
node_server_1 | SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10002ms
node_server_1 | (pool connections: active=0 idle=0 limit=10)
node_server_1 | at Object.module.exports.createError (/home/simha/app/node_modules/mariadb/lib/misc/errors.js:57:10)
node_server_1 | at Pool._requestTimeoutHandler (/home/simha/app/node_modules/mariadb/lib/pool.js:344:26)
node_server_1 | at listOnTimeout (node:internal/timers:559:17)
node_server_1 | at processTimers (node:internal/timers:502:7) {
node_server_1 | text: 'retrieve connection from pool timeout after 10002ms\n' +
node_server_1 | ' (pool connections: active=0 idle=0 limit=10)',
node_server_1 | sql: null,
node_server_1 | fatal: false,
node_server_1 | errno: 45028,
node_server_1 | sqlState: 'HY000',
node_server_1 | code: 'ER_GET_CONNECTION_TIMEOUT'
node_server_1 | }
그리고 이건 내 코드야
import dotenv from "dotenv";
import mariadb from "mariadb";
if (process.env.NODE_ENV !== "production") {
dotenv.config();
}
console.log(process.env.DB_HOST)
console.log(process.env.DB_USER)
console.log(process.env.DB_PASSWORD)
console.log(process.env.DB_NAME)
const pool = mariadb.createPool({
hostname: 'mariadb',
user: 'simha',
password: 'krishna',
database: 'blogs'
});
try {
console.log(process.env.DB_HOST,process.env.DB_USER,process.env.DB_PASSWORD,process.env.DB_NAME)
const conn = await pool.getConnection();
console.log("Connected to database.");
conn.release();
} catch (err) {
console.error("Error connecting to database:", err.message);
console.log(err)
await pool.end();
process.exit(1);
}
export default pool;
명령줄을 사용하여 데이터베이스에 연결할 수 있는 경우
mariadb --host mariadb -P 3306 --user simha –pkrishna
무엇이 문제인지 이해할 수 없는
이는 "네트워크 연결" 문제일 수 있습니다.
Q: 명령줄을 확인한 호스트와 동일한 IP를 가진 동일한 호스트에서 노드 앱이 실행되고 있습니까?
예:
https://stackoverflow.com/a/53418273/421195
문제는 phpMyAdmin에서 연결할 수 있도록 홈 IP 주소를 추가하지 않았다는 것입니다.처음 시작하는 사용자의 경우 동일한 이름과 암호로 여러 사용자를 생성하여 여러 IP(localhost, ::1 또는 127.0.0.0.1과 동일하지만 여전히 필요함)에서 실제로 액세스할 수 있습니다.
제 IP를 가리키는 동일한 자격 증명을 가진 사용자를 추가했는데 문제가 해결되었습니다.
다른 가능성:
https://stackoverflow.com/a/68406734/421195
특히 처음 몇 번은 연결이 작동하지만 그 이후에는 작동하지 않는 경우, conn.end와의 연결을 종료하지 않으면 오류가 발생할 수 있습니다.OP 문제가 아니라 다른 문제일 수도 있습니다.
마지막으로, 모든 것이 실제로 올바르게 작동할 수 있습니다.
https://stackoverflow.com/a/52225583/421195
release()를 사용하면 연결이 닫히지 않고 풀로 반환되므로 풀의 각 연결이 시간 초과됩니다.
따라서 연결이 끊기는 것은 매우 정상적이며 오류를 적절하게 처리해야 합니다.
연결이 자동으로 다시 생성됩니다. https://github.com/mysqljs/mysql#poolcluster-options 을 참조하십시오.
다음 예제에서는 유용한 팁을 제공할 수 있습니다.
https://stackoverflow.com/a/59761773/421195
setTimeout()을 사용하여 연결을 다시 시도합니다.
'use strict'; const dbpool = require('mysql').createPool({ connectionLimit: 10, acquireTimeout: 30000, waitForConnections: true, database: 'mydatabase', host: 'localhost', multipleStatements: true, password: 'mypassword', user: 'root', }); const sql = 'SELECT * FROM sometable;'; const attemptConnection = () => dbpool.getConnection((err, connection) => { if (err) { console.log('error connecting. retrying in 1 sec'); setTimeout(attemptConnection, 1000); } else { connection.query(sql, (errQuery, results) => { connection.release(); if (errQuery) { console.log('Error querying database!'); } else { console.log('Successfully queried database.'); } }); } }); attemptConnection();
언급URL : https://stackoverflow.com/questions/76378341/nodejs-not-able-to-connect-to-maria-db-able-to-connect-through-command-line
'programing' 카테고리의 다른 글
| 레이저 뷰 엔진이 장착된 ASP.NET MVC 3의 부분 뷰에서 특정 섹션으로 컨텐츠 주입 (0) | 2023.07.05 |
|---|---|
| Python 스크립트가 실행을 완료하는 데 소요된 시간 확인 (0) | 2023.07.05 |
| Mongo 오류:잘못된 작업, 대량 작업 없음 (0) | 2023.07.05 |
| Java Oracle 예외 - "목록의 최대 식 수는 1000개입니다." (0) | 2023.07.05 |
| '--color' 및 '--format specdoc' 옵션을 설정한 상태로 유지하도록 RSpec을 글로벌하게 구성하려면 어떻게 합니까? (0) | 2023.07.05 |