I am trying to connect From Node.js on Localhost to MySQL instance running on docker using docker-compose.
Node.js gives me this error: ENOTFOUND db, Full error message bellow.
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Application Name: RESTFull API - Development
Environment: development
Server is listening on port 3000
getaddrinfo ENOTFOUND db # <------------ Error here
[nodemon] app crashed - waiting for file changes before starting...
Here is docker-compose.yml that contains MySQL and adminer services.
## docker-compose.yml
version: '3.8'
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: 'nodejs-restfull-api-development'
expose:
- 3306
volumes:
- db-config:/etc/mysql
- db-data:/var/lib/mysql
adminer:
image: adminer:latest
depends_on:
- db
environment:
ADMINER_DEFAULT_DB_DRIVER: mysql
ADMINER_DEFAULT_DB_HOST: db
ADMINER_DESIGN: nette
ADMINER_PLUGINS: tables-filter tinymce
ports:
- "8080:8080"
volumes:
db-config:
db-data:
Here is my node.js database connection config.
const database = mysql.createConnection({
host: 'db',
user: config.get('db.user'),
password: config.get('db.password'),
database: config.get('db.database'),
port: config.get('db.port'),
connectTimeout: config.get('db.connectTimeout')
});
database.connect(err => {
if (err) {
console.log(err.message);
process.exit(1);
} else {
console.log('Connected to database');
}
});
You don't tell us, but I assume your Node app is running on the host and not in a container? If that's the case, then you need to expose the MySQL port to the host, so it's reachable. You also need to use localhost as the hostname in your configuration.
Expose the port by changing the database part of your docker-compose file to
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: 'nodejs-restfull-api-development'
ports:
- 3306:3306
volumes:
- db-config:/etc/mysql
- db-data:/var/lib/mysql
And change your Node configuration to
const database = mysql.createConnection({
host: 'localhost',
user: config.get('db.user'),
password: config.get('db.password'),
database: config.get('db.database'),
port: config.get('db.port'),
connectTimeout: config.get('db.connectTimeout')
});
Related
Windows 10, Docker Desktop + VS;
Docker-compose.yml has images:
node.js with socket.io
php 7.4-apache with socket.io
I need to connect socket.io within php-apache (website) to socket.io within node.js (server to handle data from php-apache) in one docker-compose.yml to run it in remote VM (hah, sounds like it is possible for an ordinary mortal).
First, tried to connect 2 containers within docker-compose (node.js to node.js) to be sure docker ports + socker.io ports set correct (successfully).
(Server side: socket.io listen 90 port, docker 90:90 (service name in docker-compose is node_server) || Client side: io(http://node_server:90), docker 85:85).
Confirmed, 2 containers are linked and ports are set correctly, started to make "php apache - node.js" socket-io docker-compose.yml.
My php-apache container with inner socket.io client composer link is "http://node_client:80".
When tried to connect "localhost:80" to PHP container: everything loaded fine, but error occured: net:ERR_NAME_NOT_RESOLVED (polling-xhr.js:206);
Error which I get while connecting to localhost:80 (docker php-apache container)
docker php-apache container is on 80:80 port in docker-compose.yml
request URL
I can connect to apache (it opens windows and all html stuff written in index.php), but gets an error (err_name_not_resolved) like socket.io in client-side (php-apache) can't make a request(?).
Checked for ping: both have connection (pinged node_server:90\client:80 from each terminal).
Checked "php-apache docker": "curl "http://node_server:90/socket.io/?EIO=4&transport=polling" and it also showed an information.
I do understand that some troubles have to be occured (because I connect from localhost to docker php container, and socket.io client in that container in that container gets mad(what ip to use(172.0.. or 192.168.. etc). But I have even no idea how to solve it (I need to connect somehow to index.php apache and socket.io.
I need to use php-apache and connect it to node.js, I confirmed socket.io worked in node.js - node.js, but in php-apache->node.js something happens while connection localhost.
docker-compose.yml:
version: "3"
services:
node_client:
container_name: client
image: img_client
ports:
- "80:80"
networks:
- test
node_server:
container_name: server
image: img_server
ports:
- "90:90"
networks:
- test
networks:
test:
external: true
Docker.client:
FROM php:7.4-apache
COPY ./client /var/www/html
EXPOSE 80
#(in ./client -> index.php)
./client/index.php:
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha..." crossorigin="anonymous"></script>
<script>
const socket = io(`http://node_server:90`, {
//secure: true,
//transport: ['websocket'],
//upgrade: false,
//rejectUnauthorized: false,
});
socket.on('connect',() =>{console.log(socket.id)});
</script>
Docker.server:
FROM node:alpine
COPY ./server /app
WORKDIR /app
COPY package*.json ./
COPY . .
CMD [ "node", "./server.mjs" ]
EXPOSE 90
//(in ./server -> server.mjs + node_modules)
./server/server.mjs:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const express = require('express')
const app = express();
const cors = require("cors")
//app.use(cors({}))
const server = require('http').createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
//rejectUnauthorized: false,
cors: {
origin: '*',
//methods: ["GET", "POST"],
//credentials: true,
}
});
server.listen(90, () => { console.log("Server is Ready!");});
//Also tried (90, '0.0.0.0', () => but there will be CORS troubles i believe, anyway I can't even determine the problem, but socket.io in "node.js + node.js" worked
//server.listen(PORT_SERVER, '0.0.0.0', () => { console.log("Server is Ready!");});
io.on('connection', (socket) => { console.log(`Подключился!`)});
Heh.. I tried to understand what is proxy and can it be used (nginx) somehow to connect 1th docker php-apache with CDN module (client) + 2th docker container node.js (server) all within docker-compose.yml, but gave up.
I'm trying to setup a database connection with my web-application (I'm using XAMPP - phpmyadmin).
In this milestone, I came across Node.js for the first time and managed to make the require() function to work by using browserify. This is my javascript file that is executed when clicking the Sign-Up button on the register.php.
var mysql = require('mysql');
var thisUser = mysql.createConnection({
host: "localhost",
user: "admin1",
password: "password",
database: "db_mymindmapper"
});
------------- WORKS UNTIL HERE -------------
thisUser.connect(function(error){
if(!error) {
alert("NODE CONNECTED TO MYSQL SERVER");
var sql = "INSERT INTO student_demographics (first_name) VALUES ('YOU DID IT MF')";
thisUser.query(sql, function(err, result) {
if(!err){
alert("result = " + result);
}else{
throw err;
}
});
}else{
throw error;
}
});
When I run this on a browser using my register.php file it gives the following error on the console:
Uncaught TypeError: Net.createConnection is not a function
at Connection.connect (bundle.js:34538)
at HTMLInputElement.check_Register (bundle.js:43660)
connect # bundle.js:34538
check_Register # bundle.js:43660
However when I run this in CMD using node signUp.js is works perfectly and data goes to the table on the phpmyadmin.
I know this is caused by this reason in the provided question: "You must run this particular module on Node.js only, you can't run it in a web browser."
MY QUESTION:
Is there any possible way to run this on browser so that users when accessing the register.php site could register? Do I need to change the entire structure of my code? Do I need require('http') to set a Node.js server?
So to answer my own question, I solved this by indeed creating a node.js server. To do this I used the terminal within Visual Studio Code (CMD will also work).
cd directoryOfTheApplication //(change the directory of the terminal)
npm init //(creates a package.json file within directory of the application)
npm install express //(modifies the package.json and add modules within node-modules folder)
create a new .js file in the directory (I called mine server.js).
//USE `nodemon scripts/server.js` on Terminal to autosave the server files.
//My modules
const express = require("express");
const morgan = require("morgan"); //GET INFORMATION ABOUT THE SERVER REQUESTS (OS, Browser,time, ...)
const mysql = require("mysql");
const app = express();
app.use(morgan('combined')); //'short', 'combined'
app.get("/users/:id", (req, res) => {
const userID = req.params.id;
console.log("Fetching user with id : " + userID);
//get data from DB
const connection = mysql.createConnection({
host: "localhost",
user: "admin1",
password: "secret",
database: "myDB"
});
let sql = "SELECT * FROM student_demographics WHERE id =?";
connection.query(sql, [userID], (err, rows, fields) => {
console.log("Fetching users was successful");
res.json(rows);
});
//res.end();
});
app.get("/", (req, res)=>{
console.log("responding to root route");
res.send("hello world from root");
});
app.get("/users", (req, res)=>{
const user1 = {
firstName: "name1",
lastName: "name2"
};
const user2 = {
firstName: "name3",
lastName: "name4"
};
res.json([user1, user2]);
});
app.listen(81, ()=>{
console.log("Server running on port 81");
});
Once again in terminal, you may wish to install nodemon so that you don't have to start the server manually. This will refresh and update the server when saving the file (in this case server.js). Also morgan will basically collect information regarding the request of the user. In terminal it would look like this:
PS C:\inetpub\wwwroot\mymindmapper> nodemon scripts/server.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node scripts/server.js`
Server running on port 81
Fetching user with id : 1
Fetching users was successful
::1 - - [14/Jun/2020:11:15:20 +0000] "GET /users/1 HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97
Safari/537.36"
The other module mysql is for the sake of this example, but I guess it would work with any modules. I basically followed the tutorials of this brilliant person on YT.
Setup express: NodeJS REST API: Super Simple Setup - Express & NPM (Ep1)
Setup DB: NodeJS REST API: Connecting to MySQL (Ep 2)
First, I have this code here for the server, which works perfectly
var app = require('express')();
var mysql = require('mysql');
app.get('/', function (req, res) {
res.sendFile(__dirname + "/start.html");
});
app.listen(3000);
But, if I try to create a connection to a database, it says that the connection is refused to 127.0.0.1 : 3036
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'user_data'
});
db.connect();
I am using XAMMP :
Click here -> MySQL / Apache
So what is the problem? I don't understand. I also get this error when I try to access phpMyAdmin :
Link to the error
You need to specify a port as your database is listening on a non standard port
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'user_data',
port: 3036
});
db.connect();
For phpMyAdmin, you need to find config.inc.php in phpMyAdmin's top level directory and edit the line where it says
$cfg['Servers'][$i]['port']
to the port you are using. And you need to change
$cfg['Servers'][$i]['host']
to 127.0.0.1 instead of localhost, because:
If you use localhost as the hostname, MySQL ignores this port number and connects with the socket, so if you want to connect to a port different from the default port, use 127.0.0.1 or the real hostname in $cfg['Servers'][$i]['host'].
Documentation on phpMyAdmin
I can't connect to the MySQL-database. I've googled some solutions, but none seems to work, or perhaps I haven't understood them. This is the setup:
let express = require("express");
let mysql = require("mysql");
let http = require("http");
let app = express();
http.createServer(app).listen(8000, function() {
console.log("Listening on http://localhost:" + port)
});
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: process.env.DB_PASSWORD,
database: "users",
port: 8000
});
connection.connect();
connection.query("SELECT * FROM user", function(err, rows, fields)
{
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log(rows[0]);
});
connection.end();
Tried to setup the connection with "socketPath" and with another port, but they both returned error:
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object.exports._errnoException (util.js:1034:11)
at exports._exceptionWithHostPort (util.js:1057:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1099:14)
--------------------
at Protocol._enqueue (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/vagrant/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/vagrant/app.js:12:12)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
When the connection and listen listens on same port, it doesn't return any errors, but the connection doesn't seem to initialize.
console.log(connection.connect()); // -> undefined
I'm very new to using MySQL to node so I'm probably doing this all wrong, but can't figure out what the problem is
For MAC users using MAMP
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "databasename",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
socketPath points to MAMP "mysql.sock" to permit the NodeJS/Mysql connection.
NOTE: the above connection also solves "Error: connect ECONNREFUSED 127.0.0.1:3306".
I hope this helps someone.
Change your connection.connect() to
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
so you can see errors.
EDIT:
Check bind-address and port in mysql config file (/etc/mysql/my.cnf). If your mysql server is running on host environment and node is running in guest (any virtualization like docker), set mysql server to listen on your local ip (eth0 like 192.168.0.x) and use same address in node config
As it turns out, I was a bit stupid. I was running the application on a Vagrant-server(virtual server), and I was trying to connect to my local-server. As soon as I tried to connect to the vagrant-server, everything worked properly. I also didn't have mysql-server properly installed to my vagrant machine.
if you don't set the port or set it to mysql default port i.e 3306 it works fine.
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "mysqluser",
password: 'password',
database: "yourdatabase"
});
I don't know the exact cause(although i tried with different ports), why it's not running on different ports but here is a link that shows how to use different port number for connecting mysql.
FYI: You are setting your app to run on 8000 and again the port mysql
using in your app is 8000.You must change it to something else.
You have to set socketPath and before you run your script make sure your MAMP is running or not.
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
Remove your port key value(port: 8000) and socketPath if you added,
from sql configuration, and try.
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "root",
database: "users"
});
Actually you occupied 8000 port by node server so you can't assign same port to different process.
Second mysql is running on port 3306. so you could not connect mysql through different port.
You can use different port for mysql but by some proxy pass mechanism or by running mysql itself on specific port.
Please follow simple steps to start (Worked on windows Machine):
Download and install MySQL from following link click here.
Configure downloaded file (I had kept default config parameters). Please check this video link for reference
Make sure MySQL server status is on.
Now you can check connection status by using below node code.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
port: 3306
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server');
})
Start Your Mysql Server from your Xampp Control panel
I have a node.js app using the sails.js framework and I'm trying to deploy this app on the bluemix cloud service.
I am trying a MongoDB instance in compose.io and I have a rather standard connection configuration in my local.js file:
connectMongo: {
adapter: 'sails-mongo',
host: 'sl-eu-lon-2-portal.1.dblayer.com',
port: 10438,
database: 'some-db'
}
It is not working. It's not deploying.
The error it gives is:
ERR error: A hook (`orm`) failed to load!
ERR error: Error: Failed to connect to MongoDB.
This means, of course, that the database is
But strangely it also gives this
ERR { [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
Which doesn't make any sense, as I am not using port 27017, as noted above I am using 10438.
The app is running locally, so I get that I am missing something on connecting to the database via the bluemix configurations, but I can't understand how come the 27017 pops up there.
So your setup seems correct. Compare it with my setup:
env/production.js
connections: {
prodMongoDb: {
adapter: 'sails-mongo',
host: process.env.MONGO_PORT_27017_TCP_ADDR,
port: 27017,
database: 'my_database'
}
},
models: {
connection: 'prodMongoDb',
migrate: 'safe'
}
env/development.js
connections: {
devMongoDb: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
database: 'my_database'
}
},
models: {
connection: 'devMongoDb',
migrate: 'safe'
}
The fact that you are specifying a port 10438 but get an error regarding 27017 means that sails is not picking up your connection definition. How do you start your app?
Starting it like this:
npm start NODE_ENV="production"
will make sails pick up the production config.