I’m running a server on c9.io using Node.js and trying to connect to Mysql
I guess I get this error:
Error: getaddrinfo ENOTFOUND
because the connection to the db is wrong.
I’m using this:
var connection = mysql.createConnection({
host: "REMOTE_ADDR",
user: "MYUSERNAME", // this is replaced by my username
database: "c9",
port: 3306
});
Any idea what’s wrong?
Thanks!
hong4rc
3,9494 gold badges20 silver badges40 bronze badges
asked Aug 27, 2014 at 7:55
After one hour, and I don’t know why, I found the issue.
In my case I replaced
host: 'localhost'
by
host: '127.0.0.1'
answered Mar 20, 2016 at 21:28
0
I know it’s been a while since this was asked but I spent the better part of today trying to fix this. What to check for:
Within your nodejs source:
- Try it without the ‘port’ option unless on your db VM, MySQL is
listening on a port besides 3306. I had this option specified but had
connection problems until I removed it. And 3306 is already the
default value for the option anyway. - Try it with the actual host IP in the host ‘option’. I was using an actual domain name and, more often than not, node-mysql would throw
the same exact «errorError: getaddrinfo ENOTFOUND» When I used the IP
address, no more errors. Also, I did not get this error while on
Ubuntu instances in AWS. As soon as I switched over to Ubuntu VMs in
Azure, I got the problem. - Set the «debug» connection option to true which will give you a verbose trace of what’s happening during the connection
On your db VM/Box/Instance:
- Ensure that MySQL is listening on the right port
- If you’re seeing the error when trying to make concurrent connections using a pool, check that your max_connections and max_user_connections haven’t been changed from the default settings in my.conf
- Monitor «SHOW PROCESSLIST;» in MySQL to see if you see any issues there
answered Dec 5, 2014 at 4:30
Scott GraphScott Graph
5275 silver badges11 bronze badges
2
This code works for me.
var mysql = require('mysql');
var con = mysql.createConnection({
host: '127.0.0.1',
port: '3306',
user: 'yourUsername',
password: '**********'
});
con.connect(function(err){
if(err) throw err;
console.log('connected!');
});
the host and port name find them in your mysql server.
in-place of ‘127.0.0.1’ you can use ‘localhost’
answered Feb 5, 2019 at 22:50
1
I was facing this issue. I did fix it simply you have to change your configuration of a connection string like if you are running on local machine try
host:’localhost’ or host:’127.0.0.1′
…and set your user name and if you want this to publish your code on server then give the host according to server if in docker container give it name host:’db’.
Zain Arshad
1,8751 gold badge11 silver badges25 bronze badges
answered Apr 17, 2019 at 6:03
zshan4444zshan4444
3203 silver badges6 bronze badges
I almost spend two hours to understand what is the problem with the mysql database. I am using Windows cmd.
I tried multiple ways e.g
npm install mysql2
- Changing
localhost to 127.0.0.1
- Refreshing node
so in order to resolve this issue
[Error: getaddrinfo ENOTFOUND 127.0.0.1:3306]
I open XAMPP and start the MySQL database then manually check the credentials and works fine for me.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'test',
password: 'test123',
});
answered Apr 8, 2020 at 12:11
OmoreOmore
6046 silver badges18 bronze badges
Hi. I’m trying to implement express in my react application to access my database tables and for that I came across this package. I implemented a server
folder (which starts along with the yarn start
script via concurrently
and nodemon
) with index.js
like this:
const express = require('express');
const mysql = require('mysql');
const app = express();
const con = mysql.createConnection({
host: 'xxxxx',
user: 'xxxxx',
password: 'xxxxx',
database: 'xxxxx',
});
con.connect( err => {
if (err) {
console.log(err);
}
})
app.get('/api/fetch-list', (req, res) => {
// code to fetch
});
const PORT = 3001;// process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`App server now listening on port ${PORT}`);
});
Then, the route/path /api/fetch-list
gets called in this component:
import React from 'react';
import axios from 'axios';
function renderTable() {
axios.get(`${process.env.PUBLIC_URL}/api/fetch-list`).then(res => {
console.log(res.data);
});
}
export function component() {
return (
<div>
{renderTable()}
</div>
);
}
And this component is rendered once I go to http:localhost:3000/table
. So once I run the project and go to that address, I get the following error in the terminal console:
{ Error: getaddrinfo ENOTFOUND xxxxx xxxxx:3306
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
--------------------
at Protocol._enqueue (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/Connection.js:119:18)
at Object.<anonymous> (/home/gfcf14/Desktop/greendream-redesign/src/server/index.js:27:5)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'xxxxx',
host: 'xxxxx',
port: 3306,
fatal: true }
I’m not certain why this could be happening. I know the credentials I use are correct given that this works on my website on old php code. For a moment I thought this may have to do with where my db is, as I have it hosted on 1&1 (ionos) and they don’t grant me a dedicated server. So I changed the credentials to a gearhost space where I have another database (the credentials of which I still use) and I get this error instead:
{ Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'xxxxx'@'myipaddress' (using password: YES)
at Handshake.Sequence._packetToError (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/sequences/Sequence.js:47:14)
at Handshake.ErrorPacket (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/sequences/Handshake.js:123:18)
at Protocol._parsePacket (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Protocol.js:291:23)
at Parser._parsePacket (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Parser.js:433:10)
at Parser.write (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Parser.js:43:10)
at Protocol.write (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Protocol.js:38:16)
at Socket.<anonymous> (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/Connection.js:91:28)
at Socket.<anonymous> (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/Connection.js:525:10)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
--------------------
at Protocol._enqueue (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/home/gfcf14/Desktop/greendream-redesign/node_modules/mysql/lib/Connection.js:119:18)
at Object.<anonymous> (/home/gfcf14/Desktop/greendream-redesign/src/server/index.js:27:5)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlMessage: 'Access denied for user 'xxxxx'@'myipaddress' (using password: YES)',
sqlState: '28000',
fatal: true }
So it doesn’t work for that one either. I might have to check the permissions for that site (which at simple sight seem to be READ & WRITE
), but how could I get the connection for the first database to work? Please let me know if you see something I may have missed
#mysql #docker #express
Вопрос:
Я пытаюсь создать проект Docker, содержащий серверную часть (express.js), контейнеры с графическим интерфейсом(Angular) и базой данных(MySQL). Каждый контейнер работает правильно по отдельности, но когда я пытаюсь установить соединение между базой данных и серверной частью, я получаю следующую ошибку.
Файловый состав проекта выглядит следующим образом.
Мой файл docker-compose выглядит следующим образом.
version: '3.8' services: gui: container_name: gui-container restart: always build: ./gui ports: - '4200:4200' environment: NODE_ENV: dev DEBUG: 'true' volumes: - ./gui:/usr/src/app/gui - /usr/src/app/gui/node_modules links: - backend command: npm run start backend: container_name: backend-container restart: always # command: sh -c "npm cache clean --force amp;amp; npm start" build: ./backend ports: - 3000:3000 volumes: - ./backend:/usr/src/app/backend - /usr/src/app/backend/node_modules environment: NODE_ENV: dev DATABASE_HOST: database depends_on: - database # command: npm run debug database: build: ./database container_name: database-container command: --default-authentication-plugin=mysql_native_password restart: always ports: - 3318:3306
My config file is the following.
var mysql = require("mysql"); function DataBaseHandler() { this.connection = null; } DataBaseHandler.prototype.createConnection = function () { console.log("Trying to connect to database."); this.connection = mysql.createConnection({ host: 'database', user: 'root', password: 'testingpassword', database: 'KuoteSuite', port: 3318 }); this.connection.connect(function (err) { if (err) { console.error("error connecting " err.stack); return null; } console.log("connected as id " this.threadId); }); return this.connection; }; module.exports = DataBaseHandler;
Я пытаюсь установить связь внутри lead.repository.js файл внутри серверной части/репозиториев.
const Lead = require('../models/lead'); const mysql = require('mysql'); var DataBaseHandler = require("../config/DataBaseHandler"); var dataBaseHandler = new DataBaseHandler(); var connection = dataBaseHandler.createConnection(); const table = 'Lead'; // Repository uses Object Models to interact with Tables from Databases class LeadRepository{ async getAllLeads(){ const result = await connection.query(`SELECT * FROM ${table}`); console.log("Leads in repository= " result); await connection.commit(); return result; } } module.exports = LeadRepository;
Комментарии:
1. Похоже, вы включили в свой вопрос несколько файлов изображений, в которых вы ссылаетесь на сообщения об ошибках, код, файлы YAML и т. Д. Можете ли вы удалить их и заменить фактическим текстом? Как бы то ни было, я не могу запустить это или скопировать части кода в ответ.
2. Я загрузил код в текстовом виде.
Ответ №1:
Соединения между контейнерами игнорируют Compose ports:
(если они вообще присутствуют). В вашей конфигурации вам всегда нужно подключаться к порту по умолчанию port: 3306
; поскольку это порт по умолчанию, вы, вероятно, можете опустить эту конфигурацию.
Также рассмотрите возможность настройки этих параметров с помощью переменных среды, поскольку в разных средах они будут отличаться. Например, параметры подключения будут отличаться при выполнении одного и того же кода для одной и той же контейнеризованной базы данных, если приложение работает в контейнере или в среде разработки без контейнеров, и они снова будут отличаться, если вы работаете в производственной среде с размещенной в облаке базой данных без контейнеров.
this.connection = mysql.createConnection({ host: process.env.DATABASE_HOST || 'localhost', user: process.env.DATABASE_USER || 'root', password: process.env.DATABASE_PASSWORD || 'testingpassword', database: process.env.DATABASE_DATABASE || 'KuoteSuite', port: process.env.DATABASE_PORT || 3306 // not 3318 });
# Local development: export MYSQL_HOST=localhost MYSQL_PORT=3318 npm run dev
# Compose setup: version: '3.8' services: database: build: ./database ports: # ignored for inter-container connections - '3318:3306' backend: build: ./backend depends_on: - database ports: - '3000:3000' environment: NODE_ENV: dev DATABASE_HOST: database DATABASE_PORT: '3306' # default MySQL port, not remapped ports:
Ответ №2:
Имейте в виду docker-compose
, что по умолчанию в качестве имени хоста используется имя службы. Поэтому, если вы хотите подключиться database
из другого контейнера в том же docker-compose.yml
файле, вы должны использовать имя службы в качестве имени хоста. В вашем случае вам следует изменить хост базы данных на: http://database
вместо 127.0.0.1
в вашей DatabaseHandler
строке 11
.
И порт в 3318
on-line 15
, как вы объявили в своем docker-compose.yml
порту для порта базы данных 3318
вместо 3306
. Имейте в виду, что для переноса синтаксис таков: HOST_PORT:CONTAINER_PORT
.
Комментарии:
1. Спасибо вам за вашу помощь! Я изменил объявление соединения следующим образом, но, похоже, это не работает.
this.connection = mysql.createConnection({ host: 'http://database', user: 'root', password: 'testingpassword', database: 'KuoteSuite', port: 3318 });
2. Я гесс
host
простоdatabase
безhttp://
своего . В противном случае вам нужно получить доступ к контейнеруcurl
, чтобы узнать, естьcurl http://database:3318 -v
ли соединение или есть ли проблемы с именем пользователя и паролем.3. Я попытался подключиться с помощью MySQLWorkbench, и мне это удалось успешно. Я не понимаю, почему он не может подключиться в бэкэнде.
4. Мне удалось выполнить локальный узел curl:3318-v, но базы данных curl нет:3318 -v Вот результат: * Попытка ::1:3318… * Подключен к localhost (::1) порт 3318 (#0) gt; GET / и протокол HTTP/1.1 gt; ведущий: локальный:3318 gt; пользователь-агент: завиток/7.77.0 gt; принимаем: / gt; * полученных по HTTP/0.9, когда не допускается * закрытие соединения 0 завиток: (1) полученные протокола HTTP/0.9, когда не допускается
5. Ты свернулся калачиком из другого контейнера? Итак, сначала запустите
docker exec -it backend-container bash
, а затем, я думаю, вам нужно установить curl черезapt-get update amp;amp; apt-get install -y curl
, а затемcurl http://database:3318 -v
. Localhost будет работать только с вашей хост-машины.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.