Error accessing remote DB with sequelize via tunnel-ssh - mysql

I have an EC2 Ubuntu instance on AWS with MySQL DB which I can access with the following configuration via HeidiSQL and everything works fine. My main goal is to connect to this DB through sequelize. I have tried to do it with npm package tunnel-ssh but constantly getting errors.
Settings
SSH Tunnel Settings
AWS EC2 Instance security group settings:
Error message:
{ SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
at Utils.Promise.tap.then.catch.err (G:\study\ssh-tunnel\sqlize-ssh\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:139:19)
at tryCatcher (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\promise.js:690:18)
at _drainQueueStep (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (G:\study\ssh-tunnel\sqlize-ssh\node_modules\bluebird\js\release\async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
name: 'SequelizeConnectionRefusedError',
parent:
{ Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true },
original:
{ Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true } }
packages I use: mysql2, sequelize, tunnel-ssh
I think so far I was able to open the ssh-tunnel and run sequelize but with errors. This is the code I've written:
const fs = require('fs');
const Sequelize = require("sequelize");
const tunnel = require('tunnel-ssh');
const ppk = fs.readFileSync('./sample.ppk', 'utf-8');
const sequelize = new Sequelize('test', 'login', 'password', {
host: 'localhost',
port: 3306,
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
const sshConfig = {
user: 'ubuntu',
host: 'sshServer',
port: 22,
dstHost: 'localhost',
dstPort: 3306,
localHost: 'localhost',
localPort: 3307,
privateKey: ppk
}
// initiate tunnel
tunnel(sshConfig, (error, server) => {
if(error) {
console.error(error);
} else {
console.log('server:', server);
sequelize
.authenticate()
.then((db) => {
console.log('CONNECTION ESTABLISHED! ', db);
})
.catch((err) => {
console.error('UNABLE TO ESTABLISH CONNECTION: ', err);
})
}
})

The issue was resolved by not using ssh-tunnel connection at all. I opened mysql port only for my home ip instead and created a new user with all permissions granted.
Fixed my code a bit: added a server's ip address instead of localhost. It works now.
const sequelize = new Sequelize('DBname', 'userName', 'password', {
host: 'ec2-xx-xxx-xx-x.ap-xxxxxxxxxxxx.compute.amazonaws.com',
port: 3306,
dialect: "mysql",
});

for mysql/aurora there custom Ip address if your script running locally on that EC# then you will be able make connection.
Add one rule with anywhere access and try it. for mysql

Related

Using Environment Variables to initialise MySQL connection in NextJS leads to 'ER_NOT_SUPPORTED_AUTH_MODE' error

I am trying to fetch data from a MySQL table. It works perfectly when I hardcode the configuration. But when I use env variables to configure it, I get the following error:
code: 'ER_NOT_SUPPORTED_AUTH_MODE',
errno: 1251,
sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',
sqlState: '08004',
fatal: true
This is my .env.local file:
MYSQL_HOST: localhost
MYSQL_USER: root
MYSQL_PASSWORD:************
MYSQL_DB:***
this is my db connections code:
const mysql = require("mysql");
var db = mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB,
});
db.connect((err) => {
if (err) {
console.log(err);
} else {
console.log("connected to db");
}
});
module.exports = db;
The issue is resolved. I used ':' instead of '='.

How to connect not to local MySQL db (PHPMyAdmin) by using React.js?

I am pretty new at Node.js, and I have existing database uploaded to Dreamhost, which has database PhpMyAdmin. I have created new React application, and by using my server folder I am trying to connect to that database. I am using Windows 10, and I run at http://127.0.0.1:5000/. This is my code:
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express()
const port = process.env.PORT || 5000
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// MySQL
const pool = mysql.createPool({
connectionLimit: 10,
user: "root",
host: '127.0.0.1',
password: "password",
database: "testdb_org"
})
// Get all info
app.get('/', (req, res) => {
pool.getConnection((err, connection) => {
res.send('TEST '+ JSON.stringify(err))
/*if (err) throw err
console.log(`Connected as id ${connection.threadId}`)
connection.query('SELECT * from users', (err, rows) => {
connection.release() // Return the connection to pool
if (!err) {
res.send(rows)
} else {
console.log(err)
}
})*/
})
})
app.listen(port, () => console.log(`Listen on port ${port}`))
res.send gives me following error:
{"code":"ER_ACCESS_DENIED_ERROR","errno":1045,"sqlMessage":"Access denied for user 'root'#'localhost' (using password: YES)","sqlState":"28000","fatal":true}
And when I open comment brackets it gives me following console error:
if (err) throw err
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
--------------------
at Protocol._enqueue (C:\Users\*\Documents\project\server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\*\Documents\project\server\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\*\Documents\project\server\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\*\Documents\project\server\node_modules\mysql\lib\Pool.js:48:16)
at C:\Users\*\Documents\project\server\app.js:24:10
at Layer.handle [as handle_request] (C:\Users\*\Documents\project\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\*\Documents\project\server\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\*\Documents\project\server\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\*\Documents\project\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\*\Documents\project\server\node_modules\express\lib\router\index.js:284:15 {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
Ok, the problem that it's not possible with online database and localhost of React.js. For connection I had to download .sql database, insert and run it locally with XAMPP control panel.

I can't connect to mysql database using process.env.variable

my config.env file
PORT=5000
DB_HOST='localhost'
DB_PORT=3306
DB_USER='root'
DB_PASSWORD='fast'
DB_NAME='hms'
my dbconnect file(in same directory as config.env file)
I cannot connect using process.env but if I directly type values like I have did in commented code then it will connect to database. Also if I console.log values of process.env.anyvariable then I will get the correct value of env variable but if i assign it to some variable like suppose const variable=process.env.DB_HOST then it will be undefined in console.log. It is throwing me this error
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlMessage: "Access denied for user ''#'localhost' (using password: NO)",
sqlState: '28000',
fatal: true
const mysql = require("mysql")
const dotenv = require("dotenv")
dotenv.config({ path: './config.env' });
const connection = mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
})
// const connection = mysql.createConnection({
// host: 'localhost',
// port: 3306,
// user: 'root',
// password: 'fast',
// database: 'hms'
// })
connection.connect( (err) => {
if (err){
console.log(err)
}
else
{
console.log("Database connected!")
}
})
my /config/config.env is not in the parent directoy so instead of
dotenv.config({ path: './config.env' });
write
dotenv.config({ path: __dirname + '/config.env' });

connection to a remote mysql database using node

Good mornig to you guys. I want to establish a connection to a remote mysql database using node js. but i am facing this error. I do not know if I wrongly specifies the access path to the db
code
var mysql = require('mysql');
var pool = mysql.createPool({
host: "http://kamerun-it.com/mysql",
connectionLimit : 100,
database: "****",
user: "****",
password: "*****",
multipleStatements: true
});
error
throw err;
^
Error: getaddrinfo ENOTFOUND http://kamerun-it.com/mysql
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
--------------------
at Protocol._enqueue (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (F:\kamerun it\aspi-api\node_modules\mysql\lib\Connection.js:119:18)
at Pool.getConnection (F:\kamerun it\aspi-api\node_modules\mysql\lib\Pool.js:48:16)
at Object. (F:\kamerun it\aspi-api\app\model\db.js:16:8)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http://kamerun-it.com/mysql',
fatal: true
}
You probably have an error in your config with the host URL.
Here's a working example with a connection to a remote MySQL:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
and here's one with mistaken host parameter:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "WRONGremotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
The second one returns the same ENOTFOUND error.
Check if that's the correct URL, if the database can be accessed remotely and via which port you can use it.

Connecting Node VM to SQL VM on VPN Azure

I have two VM on Azure:
Machine A: is the server which run a Nodejs application
Machine B: is a VM which is running a mysql instance
Machine A and B are in the same VPN, either with a local address. I tested the connection from Machine A to B using ping and it works.
My problem is regarding the database connection from the nodejs app and mysql instance.
app.js
var express = require('express'),
config = require('./config/config'),
db = require('./app/models');
var app = express();
module.exports = require('./config/express')(app, config);
db.sequelize
.sync()
.then(function () {
if (!module.parent) {
app.listen(config.port, function () {
console.log('Express server listening on port ' + config.port);
});
}
}).catch(function (e) {
throw new Error(e);
});
config.js
var path = require('path'),
rootPath = path.normalize(__dirname + '/..'),
env = process.env.NODE_ENV || 'production';
var config = {
development: {
root: rootPath,
app: {
name: 'api-http-revo'
},
port: process.env.PORT || 3000,
db: 'mysql://localhost/api-http-revo-development'
},
test: {
root: rootPath,
app: {
name: 'api-http-revo'
},
port: process.env.PORT || 3000,
db: 'mysql://localhost/api-http-revo-test'
},
production: {
root: rootPath,
app: {
name: 'api-http-revo'
},
port: process.env.PORT || 3000,
db: {
host: '10.0.0.4', //Local Ip address on VPN
user: 'myusername',
password: 'mypassword',
database: 'db-revo',
port: 3306
}
}
};
module.exports = config[env];
ERROR on 'npm start':
Unhandled rejection Error: SequelizeConnectionRefusedError: connect
ECONNREFUSED 10.0.0.4:3306
at /home/giovannimarino/api-http-revo/app.js:20:11
at tryCatcher (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/promise.js:689:18)
at Async._drainQueue (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (/home/giovannimarino/api-http-revo/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate [as _immediateCallback] (timers.js:383:17)
The following screenshot are the firewall configuration:
Machine B:
Machine A
This might be due to firewall blocking your DB connections. To confirm do a telnet on the port 3306 and if it's found to be blocking then setup an inbound rule for allowing network traffic on port 3306 on both the systems.
More information here on how to setup network traffic rules.